.NET Core DI:无法使用来自单例的作用域服务
.NET Core DI: Cannot consume scoped service from singleton
我有一个class这样的
public class KReport : IReport
{
private readonly EDevContext _context;
private readonly IMapper _mapper;
public KReport(EDevContext context, IMapper mapper = null)
{
_context = context;
_mapper = mapper;
}
public void GetKReport(int reportId,int page=1)
{
string s;
//some logic here
if(reportId==1){
GetKReport(452,2)
}
}
}
同样在启动时我添加了一个单例服务
services.AddSingleton<IKReport, KReport>();
但是当我执行应用程序时出现此错误
System.AggregateException: 'Some services are not able to be
constructed (Error while validating the service descriptor
'ServiceType: common.IKReport Lifetime: Singleton ImplementationType:
common.KReport': Cannot consume scoped service
'Models.EPMO_DevContext' from singleton 'common.IKnReport'.)'
当该递归调用被注释时不会发生此错误
真的很抱歉,我对这种依赖注入或单例服务的理解几乎为零。所以我不明白这里发生了什么
您必须在 services.AddSingleton<IKReport, KReport>();
之前添加 EDevContext 服务
编辑:
从跟踪堆栈中,显示您的 class EDevContext 是 addScopeService ,您需要使 EDevContext 和 KReport 具有相同的生命周期
这是因为您在 KReport 中注入了作用域服务。
在“Startup.cs”文件中使用以下代码。
services.AddScoped<IKReport,KReport>();
我有一个class这样的
public class KReport : IReport
{
private readonly EDevContext _context;
private readonly IMapper _mapper;
public KReport(EDevContext context, IMapper mapper = null)
{
_context = context;
_mapper = mapper;
}
public void GetKReport(int reportId,int page=1)
{
string s;
//some logic here
if(reportId==1){
GetKReport(452,2)
}
}
}
同样在启动时我添加了一个单例服务
services.AddSingleton<IKReport, KReport>();
但是当我执行应用程序时出现此错误
System.AggregateException: 'Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: common.IKReport Lifetime: Singleton ImplementationType: common.KReport': Cannot consume scoped service 'Models.EPMO_DevContext' from singleton 'common.IKnReport'.)'
当该递归调用被注释时不会发生此错误
真的很抱歉,我对这种依赖注入或单例服务的理解几乎为零。所以我不明白这里发生了什么
您必须在 services.AddSingleton<IKReport, KReport>();
编辑: 从跟踪堆栈中,显示您的 class EDevContext 是 addScopeService ,您需要使 EDevContext 和 KReport 具有相同的生命周期
这是因为您在 KReport 中注入了作用域服务。
在“Startup.cs”文件中使用以下代码。
services.AddScoped<IKReport,KReport>();