In my function app (.NET 7.0, Isolated Worker), I have one particular dependency that uses an API key, something that needs to be put in a secret store. I'm using User Secrets for local development, but I'm stuck on how to access those secret values when configuring services for dependency injection:
// secrets.json
{
"apiKey": "1234567890"
}
// Program.cs
var host = new HostBuilder()
.ConfigureFunctionsWorkerDefaults()
.ConfigureServices(s =>
{
string apiKey = ???; // how to access user secrets here?
s.AddScoped<IMyDependency>(sp => new MyDependency(apiKey));
});
.Build();
}
host.Run();
There is guidance from Microsoft on using User Secrets:
But neither of these solutions offer what I need, which is a way to access user secret values when setting up dependency injection. Instead, the recommended solution makes the configuration values themselves injected dependencies, which I can't use.
Things I've tried:
- Using
Environment.GetEnvironmentVariable
, which doesn't return a value. - Adding the user secrets configuration provider using
builder.AddUserSecrets
. I don't know whether this is necessary to do, but even if it is, I still don't know how to access the configuration when setting up DI.