Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding scoped Service Throws an exception

I wrote a simple code in Asp.net.
Adding Scoped service to builder generates this error:

System.InvalidOperationException
HResult=0x80131509
Message=Cannot resolve scoped service 'tasks.IMyLogger' from root provider.
Source=Microsoft.Extensions.DependencyInjection

My code is trivial:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddScoped<IMyLogger,ConsoleLogger>();

var app = builder.Build();

app.UseMiddleware<LogMiddleware>();

app.Run();

My Middleaware:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class LogMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IMyLogger _logger;

    public LogMiddleware(RequestDelegate next, IMyLogger logger)
    {
        _next = next;
        _logger = logger;
       
    }

    public Task Invoke(HttpContext httpContext)
    {
        _logger.Info("In Logger MiddleWare");
        return _next(httpContext);
    }
}

If I Try to add the service as singleton It works just fine.

I would love your assistance.

>Solution :

I assume you are trying to inject the logger into your custom middleware class?

Here is an example using a scoped service:

public class LogMiddleware
{
    private readonly RequestDelegate _next;

    public LogMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task InvokeAsync(HttpContext context, IMyLogger logger)
    {
        // Use logger + other logic

        await _next(context);
    }
}

Note how we are injecting the logger in the InvokeAsync method?
Since middleware classes are only instantiated once, you can only use singletons there. (I suppose transient will also work but it feels a bit odd to me)

If you need anything that is instantiated per request, you need to either add it to the InvokeAsync method signature or request for it from the HttpContext.

Documentation: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-7.0#per-request-middleware-dependencies

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading