I'm migrating an Azure Function from v1 (.NET 4.7) to v2 (.NET Standard 2). In the v1 version I was using some static variables which I read from the config like this to get a singleton (of a Cosmos DB client)
private static string cosmosDbUri = ConfigurationManager.AppSettings["CosmosDb.Uri"];
//...
private static MyCosmosDbClient cosmosDbClient = new MyCosmosDbClient(cosmosDbUri, ...);
For v2 I would switch to ConfigurationBuilder for my config:
private static IConfigurationRoot config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
Now there is the problem that this needs the ExecutionContext, which I only get (or know how to get), when the function is executed.
So my question is, how to tackle this best? Build an Init(ExecutionContext context)
method that I would call only if the config was not yet loaded or are there better ways to do this?
You can replace context.FunctionAppDirectory
with Environment.CurrentDirectory
.
At least, that works locally and that's exactly where you need local.settings.json
to work, so this change should be safe.
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