Cannot resolve scoped service from root provider .Net Core 2

后端 未结 4 690
心在旅途
心在旅途 2020-12-07 19:45

When I try to run my app I get the error

InvalidOperationException: Cannot resolve \'API.Domain.Data.Repositories.IEmailRepository\' from root provider beca         


        
4条回答
  •  孤街浪徒
    2020-12-07 20:15

    You registered the IEmailRepository as a scoped service, in the Startup class. This means that you can not inject it as a constructor parameter in Middleware because only Singleton services can be resolved by constructor injection in Middleware. You should move the dependency to the Invoke method like this:

    public ExceptionHandlingMiddleware(RequestDelegate next)
    {
        _next = next;
    }
    
    public async Task Invoke(HttpContext context, IEmailRepository emailRepository)
    {
        try
        {
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            await HandleExceptionAsync(context, ex, emailRepository);
        }
    }
    

提交回复
热议问题