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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With