简体   繁体   中英

How to use ConfigurationBuilder staticly in an Azure Function v2 (core)?

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.

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();
}

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();

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?

We can use

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

Or simply

Environment.GetEnvironmentVariable("CacheConnection");

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM