Cannot resolve scoped service from root provider .Net Core 2

后端 未结 4 685
心在旅途
心在旅途 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:20

    Your middleware and the service has to be compatible with each other in order to inject the service via the constructor of your middleware. Here, your middleware has been created as a convention-based middleware which means it acts as a singleton service and you have created your service as scoped-service. So, you cannot inject a scoped-service into the constructor of a singleton-service because it forces the scoped-service to act as a singleton one. However, here are your options.

    1. Inject your service as a parameter to the InvokeAsync method.
    2. Make your service a singleton one, if possible.
    3. Transform your middleware to a factory-based one.

    A Factory-based middleware is able to act as a scoped-service. So, you can inject another scoped-service via the constructor of that middleware. Below, I have shown you how to create a factory-based middleware.

    This is only for demonstration. So, I have removed all the other code.

    public class Startup
    {
        public Startup()
        {
        }
    
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddScoped();
            services.AddScoped();
        }
    
        public void Configure(IApplicationBuilder app)
        {
            app.UseMiddleware();
        }
    }
    

    The TestMiddleware:

    public class TestMiddleware : IMiddleware
    {
        public TestMiddleware(TestService testService)
        {
        }
    
        public Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            return next.Invoke(context);
        }
    }
    

    The TestService:

    public class TestService
    {
    }
    

提交回复
热议问题