【问题标题】:.NET Core DI: Cannot consume scoped service from singleton.NET Core DI:无法使用单例的范围服务
【发布时间】: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


【解决方案1】:

这是因为您在 KReport 中注入了作用域服务。

在“Startup.cs”文件中使用以下代码。

services.AddScoped<IkReport,KReport>();

【讨论】:

  • 它现在可以工作了.. 非常感谢.. 但很抱歉,请您解释一下区别.. 我只是一个使用这些依赖注入的初学者,但仍然没有 100% 理解那到底是什么。 .
【解决方案2】:

必须在services.AddSingleton&lt;IKReport, KReport&gt;(); 之前添加EDevContext服务


编辑: 从跟踪堆栈中,显示您的类 EDevContext 是 addScopeService ,您需要使 EDevContext 和 KReport 具有相同的生命周期

【讨论】:

  • 但是为什么在启用递归调用时会发生这种情况..否则没有错误
  • @SandeepThomas 问题是因为单例只允许一个方法实例。递归调用将生成另一个方法实例,该实例必然会失败。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-09
  • 1970-01-01
  • 2019-01-08
  • 1970-01-01
相关资源
最近更新 更多