ASP.NET Core 6: Issues with Custom Middleware and Dependency Injection Lifetimes
I need help solving I'm reviewing some code and This might be a silly question, but After trying multiple solutions online, I still can't figure this out... Hey everyone, I'm running into an issue that's driving me crazy. I'm trying to implement a custom middleware in my ASP.NET Core 6 application to log request details, but I'm encountering issues with dependency injection lifetimes and service resolution. My middleware is designed to log the request path and method before passing the control to the next middleware. Hereβs the middleware code I have: ```csharp public class LoggingMiddleware { private readonly RequestDelegate _next; private readonly ILoggingService _loggingService; public LoggingMiddleware(RequestDelegate next, ILoggingService loggingService) { _next = next; _loggingService = loggingService; } public async Task InvokeAsync(HttpContext context) { await _loggingService.LogRequestAsync(context.Request.Path, context.Request.Method); await _next(context); } } ``` I registered the middleware in `Startup.cs` like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<LoggingMiddleware>(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } ``` And my `ILoggingService` is registered with a scoped lifetime: ```csharp services.AddScoped<ILoggingService, LoggingService>(); ``` However, I'm getting the following error when ASP.NET tries to resolve `ILoggingService` during middleware execution: ``` InvalidOperationException: Unable to resolve service for type 'Namespace.ILoggingService' while attempting to activate 'Namespace.LoggingMiddleware'. ``` I also tried changing the service registration to singleton, but it leads to issues with accessing the request context within `ILoggingService`. Iβve verified that `ILoggingService` is registered correctly, and I do not have any other middleware that could interfere with this. What could be the reason for this issue? How should I correctly handle the lifetimes of services used in custom middleware? Any advice or examples would be greatly appreciated. This is part of a larger CLI tool I'm building. Thanks in advance! What's the best practice here? I'm working on a CLI tool that needs to handle this. Is there a better approach? I've been using Csharp for about a year now. Could someone point me to the right documentation? Any ideas how to fix this?