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/

posted @ 2021-03-10 13:24  lishidefengchen  阅读(3010)  评论(0编辑  收藏  举报