Decide based on the state the service holds, its thread safety, and what it depends on. Decision checklist 1. Does the service hold no state, or only immutable state, and is it thread-safe? Singleton is efficient (created once). Transient is also fine if it is cheap. 2. Does it hold data for one request (current user, tenant, unit of work) or depend on DbContext? Scoped. 3. Is it lightweight, stateless and possibly mutable per use? Transient. 4. Is it expensive to create and safe to share (HTTP connection pools, Redis multiplexer, compiled regex cache)? Singleton. 5. What do its dependencies need? Its lifetime must be equal to or shorter than each dependency's lifetime. If it needs a scoped service, it cannot be a singleton. Practical examples - AppDbContext: scoped (AddDbContext default) — not thread-safe, per-request unit of work. - OrderRepository using DbContext: scoped. - OrderService using the repository: scoped. - PriceFormatter (pure function): transient or singleton. - IMemoryCache, IOptionsMonitor<T>, ILogger<T>: singleton (provided by the framework). - Typed HttpClient: registered by AddHttpClient as transient, with handlers pooled by IHttpClientFactory. - Background job services: hosted services are singletons; they create scopes to use scoped services. Validation tools - Enable ValidateScopes and ValidateOnBuild (on by default in Development) to catch lifetime mismatches and missing registrations at startup. Common mistakes and consequences - DbContext as singleton: threading exceptions and data from one user visible to others. - Scoped into singleton (captive dependency): stale data and memory leaks. - Heavy objects as transient: unnecessary allocations and GC pressure. - Mutable shared state in a singleton without synchronisation: race conditions. When unsure, start with scoped for application services in web apps. It is safe for request-based work, and you can optimise to singleton later when you know the service is stateless and thread-safe.
Ravindra Wadile · · 0 likes