Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Azure Function v2 - how to load configuration as singelton?

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?

like image 470
silent Avatar asked Dec 17 '22 23:12

silent


1 Answers

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.

like image 163
Mikhail Shilkov Avatar answered Jan 29 '23 14:01

Mikhail Shilkov