CodexBloom - Programming Q&A Platform

Issue with ASP.NET Core Dependency Injection in Scoped Services after Middleware Execution

πŸ‘€ Views: 82 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-13
asp.net-core dependency-injection middleware services C#

I'm encountering an issue with ASP.NET Core 6 where I try to use a scoped service within a middleware, but it always returns null. I have a `RequestLoggingMiddleware` that logs requests and uses a custom service `IRequestLogger` which is registered as scoped. Here’s the relevant code for my middleware and startup configuration: ```csharp public class RequestLoggingMiddleware { private readonly RequestDelegate _next; private readonly IRequestLogger _requestLogger; public RequestLoggingMiddleware(RequestDelegate next, IRequestLogger requestLogger) { _next = next; _requestLogger = requestLogger; } public async Task InvokeAsync(HttpContext context) { await _requestLogger.LogRequest(context); await _next(context); } } ``` In my `Startup.cs`, I add the middleware like this: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseMiddleware<RequestLoggingMiddleware>(); // Other middleware registrations } ``` And I register my service in the `ConfigureServices` method: ```csharp services.AddScoped<IRequestLogger, RequestLogger>(); ``` When I run the application, I get a `NullReferenceException` in the `LogRequest` method. I suspect this is happening because I'm trying to resolve `IRequestLogger` directly in the middleware constructor instead of using the built-in DI container. I've also tried injecting `IServiceProvider` and resolving the service within the `InvokeAsync` method, but that still returns null: ```csharp public class RequestLoggingMiddleware { private readonly RequestDelegate _next; private readonly IServiceProvider _serviceProvider; public RequestLoggingMiddleware(RequestDelegate next, IServiceProvider serviceProvider) { _next = next; _serviceProvider = serviceProvider; } public async Task InvokeAsync(HttpContext context) { using (var scope = _serviceProvider.CreateScope()) { var requestLogger = scope.ServiceProvider.GetRequiredService<IRequestLogger>(); await requestLogger.LogRequest(context); } await _next(context); } } ``` However, this leads to another issue where the `LogRequest` method does not behave as expected, as if the scoped instance is not being tracked properly. Could anyone provide insight into the correct approach for using scoped services in middleware? Am I missing something important in the DI configuration or middleware pipeline setup?