如何在 Azure Function v2(核心)中静态使用 ConfigurationBuilder? [英] How to use ConfigurationBuilder staticly in an Azure Function v2 (core)?

查看:26
本文介绍了如何在 Azure Function v2(核心)中静态使用 ConfigurationBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将 Azure 函数从 v1 移植到 v2 时,配置管理器用于读取 local.settings.json 的方式发生了变化.

While porting an Azure Function from v1 to v2 there is a change in how the configuration manager is used to read the local.settings.json.

之前,我使用以下代码启用函数实例之间的redis连接池:

Previously, I used the following code to enable redis connection pooling between function instances:

public static class Redis
{
    /// <summary>
    /// Initializes the REDIS connection.
    /// </summary>
    private static readonly Lazy<ConnectionMultiplexer> LazyConnection = new Lazy<ConnectionMultiplexer>(() =>
    {
        return ConnectionMultiplexer.Connect(ConfigurationManager.AppSettings["CacheConnection"]);
        });

    public static IDatabase Database => LazyConnection.Value.GetDatabase();
}

但是在 v2 中 ConfigurationManager 不再可用,我们必须使用类似的东西:

However in v2 the ConfigurationManager is no longer available and we have to use something like:

new ConfigurationBuilder()
        .SetBasePath(context.FunctionAppDirectory)
        .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
        .AddEnvironmentVariables()
        .Build();

但是,因为它需要仅在函数运行时可用的 context,所以我们无法创建一个在所有函数之间共享的静态类.是否可以在 Azure Functions v2 中静态读取 app.settings.json?

However, because it requires the context which is only available during function runtime we cannot create a static class shared across all functions. Is it possible to read the app.settings.json statically in Azure Functions v2?

推荐答案

我们可以使用

var config = new ConfigurationBuilder()
    .AddEnvironmentVariables()
    .Build();
string cacheConnection = config["CacheConnection"];

或者干脆

Environment.GetEnvironmentVariable("CacheConnection");

local.settings.json(Azure 上的应用程序设置)中的值会在函数宿主启动时自动注入 EnvironmentVariables.

Values in local.settings.json(Also Application settings on Azure) are injected into EnvironmentVariables automatically when function host starts.

这篇关于如何在 Azure Function v2(核心)中静态使用 ConfigurationBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆