其他分享
首页 > 其他分享> > net5 依赖注入的时候,遇到的问题:Cannot consume scoped service from singleton IHostedService

net5 依赖注入的时候,遇到的问题:Cannot consume scoped service from singleton IHostedService

作者:互联网

描述:

InvalidOperationException: Error while validating the service descriptor ‘ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: kafka_api_producer_consumer.TheCodeBuzzConsumer’: Cannot consume scoped service ‘SQLDBService.Context.EmployeeContext’ from singleton ‘Microsoft.Extensions.Hosting.IHostedService’.

 

 解决方式一:

使用 IServiceScopeFactory 创建我们的上下文对象:

 

 解决方式二:

使用 IServiceProvider 创建我们的上下文对象:

 

 参考:https://www.thecodebuzz.com/cannot-consume-scoped-service-from-singleton-ihostedservice/

标签:singleton,consume,service,Cannot,scoped,IHostedService
来源: https://www.cnblogs.com/lishidefengchen/p/14511053.html