简体   繁体   中英

.NET Core DI: Cannot consume scoped service from singleton

I have a class like this

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)
       }
    }
}

Also in startup I have added a singleton service

services.AddSingleton<IKReport, KReport>();

But when I execute the application I am getting this error

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'.)'

This error wont occur when that recursive call gets commented

Really sorry my understanding of this dependency injection or singleton services are almost 0. So I didnt understand what happens here

You must add EDevContext service before services.AddSingleton<IKReport, KReport>();


Edit: From the trace stack, that show your class EDevContext is addScopeService,you need make the EDevContext and KReport as the same lifetimes

It is because you are injecting scoped service in KReport.

Use following code in "Startup.cs" file.

services.AddScoped<IkReport,KReport>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM