Something beautiful is on the way.

关于.net的注入问题 singleton scope

问题:

Message=Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: xxxx Lifetime: Singlet> on ImplementationType: xxxx': Cannot consume scoped service 'SqlSugar.ISqlSugarClient' from singleton 'xxxxx'.)
意思就是说,你的服务是singleton的,你要注入个scope的,这是不被允许的。

推荐使用作用域(Scoped)生命周期:AddScoped 是最常用的注入方式

解决:
1、注入:IServiceScopeFactory factory 来创建对象:

ISqlSugarClient db=factory.Createscope().ServiceProvider.GetRequiredservice<ISqlSugarClient>();

2、注入: IServiceProvider provider 来创建对象:

ISqlSugarClient db=provider.Createscope().ServiceProvider.GetRequiredservice<ISqlSugarClient>();

3、program 降级单例模式的注入都为scope可以直接注入了。
AddScoped

posted @ 2025-05-30 16:49  张朋举  阅读(85)  评论(0)    收藏  举报