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

Viewed 4394

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?

1 Answers

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.

Related