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/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM