解决方式一: 使用IServiceScopeFactory 创建我们的上下文对象: 解决方式二: 使用IServiceProvider 创建我们的上下文对象: 参考:https://www.thecodebuzz.com/cannot-consume-scoped-service-from-singleton-ihostedservice/
.net core 依赖注入,运行报错 Cannot consume scoped 'xxx' service from singleton 'yyy' 这是因为 xxx 的生命周期是 AddScoped 注入的,而 yyy 的生命周期是 AddSingleton ,然后 yyy 这个单例的对象中,它又依赖了xxx 也就是说,单例注入的对象中依赖了 AddScoped 注入的对象。 正常来说,单例模式不该再依赖...
描述: 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 singleto...
System.AggregateException:“Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: WebApplication9.Models.BgServerTest': Cannot consume scoped service 'WebApplication9.Models....
yyy 被注册为 singleton ,yyy 通过构造函数注入了 xxx ,结果引发该异常,将 yyy 也注册为 scoped ...
在这个例子中,SingletonService 使用IServiceScopeFactory 来创建一个新的作用域,并从中解析 IScopedService。这样可以确保每次使用 IScopedService 时都获得一个新的实例。 5. 总结 "Cannot consume scoped service" 错误通常与服务的生命周期管理不当有关。要解决这个问题,你需要确保服务的注册和使用方式与其生命周期...
Scoped – they’re created once per the request (connection) Transient are created every time you request them from the DI container You should almost never consume scoped service or transient service from a singleton. You should also avoid consuming transient service from a scoped service. ...
If we access the Scoped service from a Singleton service, it will show the "CANNOT consume scoped from singlleton service" error. To solve this issue, in the Singleton service, we can access them via the IServiceProvider or IServiceScopeFactory, refer to the following sample code: T...
找到原因了,集成测试所测试的 web api 项目的 Program 中使用了AddDbContextPool,而在集成测试的Blog...
System.AggregateException:“Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: Microsoft.Extensions.Hosting.IHostedService Lifetime: Singleton ImplementationType: WebApplication9.Models.BgServerTest': Cannot consume scoped service 'WebApplication9.Models...