net核心3依赖项注入服务作为

net核心3依赖项注入服务作为

本文介绍了.net核心3依赖项注入服务作为“配置"的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚将.net核心应用程序从2.2版升级到了3版.在startup.cs的ConfigureServices方法内部,我需要解析身份验证服务使用的服务.我正在使用"services.BuildServiceProvider()"构建"所有服务,但.net core 3抱怨该方法会创建服务的其他副本,并建议我依赖注入服务作为配置"的参数.我不知道该建议意味着什么,我想理解它.

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

推荐答案

实际上,主机应自动调用ServiceCollection.BuildServiceProvider().您的代码services.BuildServiceProvider();将创建一个重复的服务提供商,该服务提供商默认为不同的,这可能会导致不一致的服务状态.请参阅引起的错误由多个服务提供商在这里.

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

这篇关于.net核心3依赖项注入服务作为“配置"的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 23:55