Tuesday, 2 December 2025

DI error

 

🔥 Why This Happens

You likely did ONE of these:

  • Registered IErrorLoggerService as Scoped, but you're calling it from:

    • Middleware constructor

    • A static class

    • A background task

    • Something running outside the HTTP request pipeline

    • Inside Program.cs directly during startup

OR

  • You forgot to register it in DI.


💯 THE FIX: Register the service + Use it correctly in middleware


1. Register your IErrorLoggerService properly

In Program.cs or ServiceExtensions:

builder.Services.AddScoped<IErrorLoggerService, ErrorLoggerService>();

2. DO NOT inject scoped services into middleware constructors

Middleware constructor runs once at startup = singleton scope
Scoped services = per request → mismatch

Bad:

public class ExceptionHandlingMiddleware { private readonly IErrorLoggerService _errorLogger; // ❌ scoped injected into singleton }

This is EXACTLY what triggers your error.


3. Proper way → Resolve inside InvokeAsync using context.RequestServices

Modify your middleware like this:

public async Task InvokeAsync(HttpContext context) { try { await _next(context); } catch (Exception ex) { // Resolve scoped service here var loggerService = context.RequestServices.GetRequiredService<IErrorLoggerService>(); await loggerService.LogErrorAsync(new ErrorLogDto { UserName = context.User?.Identity?.Name ?? "SYSTEM", ErrorMessage = ex.Message, ErrorProcedure = context.Request.Path, ErrorDateTime = DateTime.UtcNow }); throw; // continue normal exception behavior } }

This is safe because middleware resolves the scoped service per request.


🎉 This removes the error completely.


⭐ Bonus: Template for IErrorLoggerService

public interface IErrorLoggerService { Task LogErrorAsync(ErrorLogDto dto); }

Implementation:

public class ErrorLoggerService : IErrorLoggerService { private readonly UARDbContext _context; public ErrorLoggerService(UARDbContext context) { _context = context; } public async Task LogErrorAsync(ErrorLogDto dto) { var error = new TblErrors { UserName = dto.UserName, ErrorMessage = dto.ErrorMessage, ErrorProcedure = dto.ErrorProcedure, ErrorDateTime = DateTime.UtcNow }; await _context.TblErrors.AddAsync(error); await _context.SaveChangesAsync(); } }

No comments:

Post a Comment

HCL healthcare

 hcl health care f2f second round interview asked more uestions on microservice 1.apim manage all apis in one place 2.sql profiler in one fo...