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

前端 未结 1 1376
情话喂你
情话喂你 2021-01-21 09:34

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 servi

1条回答
  •  礼貌的吻别
    2021-01-21 10:19

    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();
    
    services.AddOptions(JwtBearerDefaults.AuthenticationScheme)
        .Configure((opts,jwtAuthManager)=>{
            opts.TokenValidationParameters = new TokenValidationParameters
            {
                AudienceValidator = jwtAuthManager.AudienceValidator,
                // More code here...
            };
        });
    
    services
        .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer();
    

    0 讨论(0)
提交回复
热议问题