Service Lifetimes in .NET Dependency Injection
Talk it through out loud with your AI coach.
The problem
- medium
- Pro
In an ASP.NET Core app, a service registered as a singleton takes an Entity Framework DbContext in its constructor, and under load you see strange errors about the context being used by two threads at once. Explain the three service lifetimes, what's gone wrong, and how to fix it.
What a strong answer covers
- What each lifetime means in a web app.
- How a long-lived service can trap a short-lived one.
- Ways to restructure so each request gets its own context.
- The built-in safety net that can catch this before production.
Common mistake: Fixing the errors by adding locks around the shared context instead of fixing the lifetimes.
Knowing this is half of it. Saying it clearly out loud is the part the coach helps you practise.
Practise it out loud