ASP.NET Core 6 - how to to resolve scoped service from singleton in middleware
I'm trying to figure out I'm relatively new to this, so bear with me. I'm currently developing an ASP.NET Core 6 application, and I'm working with an scenario when trying to inject a scoped service into a singleton middleware. I understand that this is generally not recommended because of the different lifetimes, but I have a specific use case where I need to access the scoped service within the middleware. I'm using the following setup in my `Startup.cs`: ```csharp public void ConfigureServices(IServiceCollection services) { services.AddScoped<IMyScopedService, MyScopedService>(); services.AddSingleton<MyMiddleware>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<MyMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` In my `MyMiddleware`, I have the following code: ```csharp public class MyMiddleware { private readonly RequestDelegate _next; public MyMiddleware(RequestDelegate next) { _next = next; } public async Task InvokeAsync(HttpContext context) { var scopedService = context.RequestServices.GetService<IMyScopedService>(); // This line throws an exception // Do something with the scoped service await _next(context); } } ``` When I run the application, I receive the following behavior message: ``` InvalidOperationException: want to resolve scoped service 'IMyScopedService' from root provider. ``` I tried changing the service lifetime of `MyMiddleware` to scoped, but that leads to other complications since itβs tied to the request lifecycle. I also considered using a factory pattern but I'm unsure how to implement it properly in this context. Any suggestions on how to resolve this scenario or alternative design patterns to achieve the desired outcome would be greatly appreciated. For context: I'm using C# on macOS. Is this even possible?