Cannot resolve scoped service from root provider


If you want to use a scoped Service in Asp.net Core 9 Middleware, you need to create a ServiceFactory first.

public class MyMiddleware
{
    private readonly RequestDelegate _next;
    private readonly IServiceScopeFactory _serviceScopeFactory;

    public MyMiddleware(RequestDelegate next, IServiceScopeFactory serviceScopeFactory)
    {
        _next = next;
        _serviceScopeFactory = serviceScopeFactory;
    }

    public async Task InvokeAsync(HttpContext context)
    {
        using (var scope = _serviceScopeFactory.CreateScope())
        {
            var myScopedService = scope.ServiceProvider.GetRequiredService<MyScopedService>();

            // Use myScopedService here as needed
            // For example, you could log information or modify the request

            // Continue processing the request
            await _next(context);
        }
    }
}





For peering opportunity Autonomouse System Number: AS401345 Custom Software Development at ErnesTech Email AddressContact: [email protected]