SOLID & Design Patterns Interview Question #141
What design considerations apply to thread-safe singleton services?
Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced
Quick Interview Answer
A singleton service is shared across concurrent requests, so mutable instance state must be safe for concurrent access. Prefer stateless or immutable singleton services whenever possible.
Detailed Explanation
A singleton service is shared across concurrent requests, so mutable instance state must be safe for concurrent access. Prefer stateless or immutable singleton services whenever possible.
A singleton should not directly depend on a scoped service such as a typical EF Core DbContext. If scoped work is genuinely required, create an explicit scope through an appropriate factory and understand the lifetime implications.
Code Example
builder.Services.AddSingleton<ICacheCatalog,
CacheCatalog>();
// Prefer immutable/concurrent state inside
// CacheCatalog when requests share it.