Cannot resolve scoped service from root provider .Net Core 2
Middleware is always a singleton so you can't have scoped dependencies as constructor dependencies in the constructor of your middleware.
Middleware supports method injection on the Invoke method,so you can just add the IEmailRepository emailRepository as a parameter to that method and it will be injected there and will be fine as scoped.
public async Task Invoke(HttpContext context, IEmailRepository emailRepository)
{
....
}
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);
}
}
Another way to get the instance of scoped dependency is to inject service provider (IServiceProvider
) into the middleware constructor, create scope
in Invoke
method and then get the required service from the scope:
using (var scope = _serviceProvider.CreateScope()) {
var _emailRepository = scope.ServiceProvider.GetRequiredService<IEmailRepository>();
//do your stuff....
}
Check out Resolving Services in a Method Body in asp.net core dependency injection best practices tips tricks for more details.