Interview frequency: …
Short answer
It happens when a shorter-lived service (such as Scoped) is injected into a longer-lived service (such as Singleton), keeping the Scoped instance in memory forever and preventing cleanup.
Explanation
If DbContext (Scoped) is injected into CacheService (Singleton), the same DbContext lives for the entire application lifetime and Dispose is never called. This can increase memory use (Memory Leak) and cause concurrent threads to share the same connection, leading to Concurrency errors. .NET's ValidateScopes option throws an exception at startup in Development if it detects this dependency.
Code example
// Enabled automatically in Development:
builder.Host.UseDefaultServiceProvider(options => {
options.ValidateScopes = true;
options.ValidateOnBuild = true;
});Common mistakes
- Disabling ValidateScopes in development to bypass the error instead of fixing the dependencies.
Follow-up questions
- How do you run continuous background tasks with BackgroundService, and what are the risks of injecting Scoped services into it?
- How do the Transient, Scoped, and Singleton service lifetimes differ in .NET?