🔥 Why This Happens
You likely did ONE of these:
-
Registered
IErrorLoggerServiceas Scoped, but you're calling it from:-
Middleware constructor
-
A static class
-
A background task
-
Something running outside the HTTP request pipeline
-
Inside
Program.csdirectly 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:
✅ 2. DO NOT inject scoped services into middleware constructors
Middleware constructor runs once at startup = singleton scope
Scoped services = per request → mismatch
❌ Bad:
This is EXACTLY what triggers your error.
✅ 3. Proper way → Resolve inside InvokeAsync using context.RequestServices
Modify your middleware like this:
This is safe because middleware resolves the scoped service per request.
🎉 This removes the error completely.
⭐ Bonus: Template for IErrorLoggerService
Implementation:
No comments:
Post a Comment