Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 216
Yellowy T. Avatar asked Jan 17 '19 15:01

Yellowy T.


People also ask

How do I use Azure function configuration?

To begin, go to the Azure portal and sign in to your Azure account. In the search bar at the top of the portal, enter the name of your function app and select it from the list. Under Settings in the left pane, select Configuration.

How do I get Azure function connection string?

Get connection informationSign in to the Azure portal. Select SQL Databases from the left-hand menu, and select your database on the SQL databases page. Select Connection strings under Settings and copy the complete ADO.NET connection string. For Azure SQL Managed Instance copy connection string for public endpoint.

How do I read app settings from Azure in .NET core?

After deploying, click on the go-to-resources. In the left side menu, click on the search box & search for configuration, click on the configuration & click on "New Application Settings", add pair of key-value which we used in our appsettings. json. Click on "save", it might take 5-10 secs to deploy the changes.


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.

like image 166
Jerry Liu Avatar answered Oct 05 '22 20:10

Jerry Liu