Reputation: 5624
I'm trying to add a configuration value to an IHostedService
but do not know how.
This is what I have at the moment:
Startup
services.Configure<MyOptions>(Configuration.GetSection("MyOptions"));
services.AddHostedService<MyHostedService>();
MyOptions
public class MyOptions
{
public string MyOption{ get; set; }
}
Appsettings
"MyOptions": {
"MyOption": "42"
}
MyHostedService
public MyHostedService(ILogger<MyHostedService> logger)
{
_logger = logger;
// Where are my options?! :(
}
Upvotes: 3
Views: 3983
Reputation: 2073
You are almost there. You got only one thing left to do:
Just use constructor dependency injection with IOptions<MyOptions>
or related (depending on your scenario) in your IHostedService
:
public MyHostedService(ILogger<MyHostedService> logger, IOptions<MyOptions> optionsAccessor)
{
_logger = logger;
_options = optionsAccessor.Value;
}
For more details, see Options pattern in ASP.NET Core.
Upvotes: 5