.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...
};
}
}
但是.net核心3抱怨该方法会创建服务的其他副本,并建议我依赖注入服务作为配置"的参数.
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'.
实际上,主机应自动调用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();