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