I'm creating a new console app for the first time in a while and I'm learning how to use IHostedService. If I want to have values from appsettings.json available to my application, the correct way now seems to be to do this:
public static async Task Main(string[] args)
{
await Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<MyHostedService>();
services.Configure<MySettings(hostContext.Configuration.GetSection("MySettings"));
services.AddSingleton<MySettings>(container =>
{
return container.GetService<IOptions<MySettings>>().Value;
});
})
.RunConsoleAsync();
}
public class MyHostedService
{
public MyHostedService(MySettings settings)
{
// values from MySettings should be available here
}
}
public class MySettings
{
public string ASetting {get; set;}
public string AnotherSetting {get; set; }
}
// appsettings.json
{
"MySettings": {
"ASetting": "a setting value",
"AnotherSetting": "another value"
}
}
And that works and it's fine. However, what if I want to get my variables not from an appsettings.json section but from environment variables? I can see that they're available in hostContext.Configuration and I can get individual values with Configuration.GetValue. But I need them in MyHostedService.
I've tried creating them locally (i.e. as a user variable in Windows) with the double-underscore format, i.e. MySettings_ASetting but they don't seem to be available or to override the appsettings.json value.
I guess this means mapping them to an object like MySettings and passing it by DI in the same way but I'm not sure how to do this, whether there's an equivalent to GetSection or whether I need to name my variables differently to have them picked up?