如何在Azure Function v2(核心)中静态使用ConfigurationBuilder? [英] How to use ConfigurationBuilder staticly in an Azure Function v2 (core)?
问题描述
在将Azure Function从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屋!