Tuesday, 2 December 2025

DI error

 

👉 When your ExceptionHandlingMiddleware tries to resolve a scoped service directly from the app root container
(which is NOT allowed).

The fix is simple — and you’re very close.
Let me give you the correct, production-safe version.


Root Cause

Your middleware is registered as a singleton (default), meaning:

  • Middleware = Singleton

  • ErrorLoggerService = Scoped

➡ Middleware cannot directly use scoped service from constructor
➡ Must resolve inside InvokeAsync() using context.RequestServices

You already attempted this — but the middleware itself still injects the service incorrectly.


Correct Fix (100% works)

❌ WRONG (current middleware constructor injects scoped service)

public ExceptionHandlingMiddleware(RequestDelegate next, IErrorLoggerService logger)

This forces the DI system to resolve IErrorLoggerService at startup (root provider).
Boom: exception.


✅ ✔ RIGHT: Middleware must NOT receive scoped services in constructor

✔ FIXED Middleware

public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; private readonly ILogger<ExceptionHandlingMiddleware> _logger; public ExceptionHandlingMiddleware(RequestDelegate next, ILogger<ExceptionHandlingMiddleware> logger) { _next = next; _logger = logger; } public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { // 🔥 Resolve scoped service CORRECTLY var errorLogger = context.RequestServices.GetRequiredService<IErrorLoggerService>(); await errorLogger.LogErrorAsync(new ErrorLogDto { UserName = context.User?.Identity?.Name ?? "SYSTEM", Path = context.Request.Path, ErrorMessage = ex.Message }, ex); await HandleExceptionAsync(context, ex); } } }

Notice:
✔ No scoped services in constructor
✔ Scoped service resolved inside request pipeline → valid


🛠 Program.cs validation (your DI is correct)

services.AddScoped<IErrorLoggerService, ErrorLoggerService>();

This is perfect.
No need to change DI.

No comments:

Post a Comment

dropdownsearch for dyanmic fields

    I’ve enabled searchable dropdowns for all dynamic dropdown controls in Assignment Details. What I changed Added a  dropdownSearch  map...