I have asp.net core application. I have Options
stored in appsettings.json file. I register the Options
with services and then trying to resolve it in Configure method.
However service provider cannot resolve option in Configure method.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.Configure<HstsOptions>(Configuration.GetSection("HstsOptions"));
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime appLifetime,IServiceProvider services)
{
var options = services.GetService<HstsOptions>();
// service provider cannot resolve options here, it returns null
app.UseHsts(options);
}
}
That's because with services.Configure<T>(...)
you register not exact T
but IOptions<T>
.
So you have two ways. Either register exact T like
services.AddScoped(provider => provider.GetRequiredService<IOptions<T>>().Value);
or get T
through IOptions:
var options = services.GetService<IOptions<HstsOptions>>().Value;
you can change the method signature of Configure and inject anything previously registered into the method like this:
public void Configure(
IApplicationBuilder app,
IHostingEnvironment env,
ILoggerFactory loggerFactory,
IApplicationLifetime appLifetime,
IOptions<HstsOptions> hstsOptions)
{
app.UseHsts(hstsOptions.Value);
}
note that when you use services.Configure you are really registering an IOptions of the thing you are registering, and to get the thing you use the .Value property of that
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