【发布时间】:2021-03-05 09:13:18
【问题描述】:
我有这样的课
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: '有些服务不能 构造(验证服务描述符时出错 'ServiceType: common.IKReport Lifetime: Singleton ImplementationType: common.KReport':无法使用范围服务 'Models.EPMO_DevContext' 来自单例'common.IKnReport'。)'
该递归调用被注释时不会发生此错误
真的很抱歉我对这种依赖注入或单例服务的理解几乎是0。所以我不明白这里发生了什么
【问题讨论】:
-
这似乎与递归方法的存在无关?听起来您正试图在单例中构造一个短暂的项目,容器将其作为对象。
-
当您在开发模式下运行时,ASP.NET Core 会抛出此错误,以警告您Captive Dependencies。
标签: c# .net-core dependency-injection singleton asp.net-core-webapi