Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ServiceProvider cannot resolve options in configure method

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);
    }

}
like image 477
LP13 Avatar asked Dec 14 '22 00:12

LP13


2 Answers

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;
like image 112
xneg Avatar answered Dec 16 '22 13:12

xneg


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

like image 45
Joe Audette Avatar answered Dec 16 '22 14:12

Joe Audette