.net core 3 dependency injecting services as parameters to 'configure'

岁酱吖の 提交于 2020-05-30 07:05:55

问题


I've just upgraded a .net core app from version 2.2 to 3. Inside the ConfigureServices method in startup.cs I need to resolve a service that is used by the authentication service. I was "building" all the services using "services.BuildServiceProvider()" but .net core 3 complains about the method creating additional copies of the services and suggesting me to dependency injecting services as parameters to 'configure'. I have no idea what the suggestion means and I'd like to understand it.

public virtual void ConfigureServices(IServiceCollection services)
{
    // Need to resolve this.
    services.AddSingleton<IManageJwtAuthentication, JwtAuthenticationManager>();

    var sp = services.BuildServiceProvider(); // COMPLAINING HERE!!
    var jwtAuthManager = sp.GetRequiredService<IManageJwtAuthentication>();

    services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(c =>
        {
            c.TokenValidationParameters = new TokenValidationParameters
            {
                AudienceValidator = jwtAuthManager.AudienceValidator,
                // More code here...
            };
        }
}

回答1:


but .net core 3 complains about the method creating additional copies of the services and suggesting me to dependency injecting services as parameters to 'configure'.

Actually, the ServiceCollection.BuildServiceProvider() should be invoked by the Host automatically. Your code services.BuildServiceProvider(); will create a duplicated service provider that is different the default one, which might lead to inconsistent service states. See a bug caused by multiple Service Provider here.

To solve this question, configure the options with dependency injection instead of creating a service provider and then locating a service.

For your codes, rewrite them as below:

services.AddSingleton<IManageJwtAuthentication, JwtAuthenticationManager>();

services.AddOptions<JwtBearerOptions>(JwtBearerDefaults.AuthenticationScheme)
    .Configure<IManageJwtAuthentication>((opts,jwtAuthManager)=>{
        opts.TokenValidationParameters = new TokenValidationParameters
        {
            AudienceValidator = jwtAuthManager.AudienceValidator,
            // More code here...
        };
    });

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer();


来源:https://stackoverflow.com/questions/58212736/net-core-3-dependency-injecting-services-as-parameters-to-configure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!