C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

Singleton vs Transient vs Scoped - lifetimes in DI

This is one of the classic SE III interview topics, because a wrongly chosen lifetime is a common source of bugs (memory leaks, state leaking between requests, race conditions). I'll go through all three with concrete .NET examples.

Transient

A new instance on every resolve.

services.AddTransient<IEmailValidator, EmailValidator>();

Every time someone asks for IEmailValidator - whether directly or as a dependency of another class - the container creates a new object.

When to use: - Lightweight, stateless services (validators, mappers, calculators) - Classes with no state at all that don't hold any resources

Pitfall: if you have a Transient service that is expensive to create (e.g. it opens a connection), and you inject it in a loop or multiple times in the same request - you waste resources.

Scoped

One instance per "scope" - in ASP.NET Core a scope = one HTTP request. In WPF or a desktop application you have to create scopes by hand (e.g. one per operation/window).

services.AddScoped<IOrderContext, OrderContext>();

Within one request, no matter how many times IOrderContext is injected into different classes - they get the same instance. But the next request will get a new one.

When to use: - DbContext in Entity Framework - the classic example. You want all repositories within one request to share the same context (the same transaction, the same change tracker), but you don't want to share it between different users/requests - Data specific to a given business operation (e.g. CurrentUserContext with the logged-in user's data for the duration of the request)

Pitfall: using a Scoped service outside a scope (e.g. in a Singleton that injects it) will throw an exception or, worse, in some configurations silently give you a "frozen" instance from the first scope - a classic bug to catch.

Singleton

One instance for the whole lifetime of the application.

services.AddSingleton<ICacheService, MemoryCacheService>();

Created once (on first use or right at startup, depending on configuration), and the same instance is returned for the whole life of the application, for all requests/threads.

When to use: - In-memory cache - Application configuration (read once from a file/env) - Clients for external services that manage their own connection pool (e.g. HttpClient via IHttpClientFactory, a Redis client) - Logger (although usually it is ILoggerFactory that is a Singleton, and the specific ILogger<T> instances may be Transient)

Pitfalls: - It must be thread-safe - a Singleton lives for the whole application, so it will be used concurrently by many threads/requests at once. If it holds mutable state without synchronisation - you have a race condition. - Memory leaks - if a Singleton holds references to large objects and never releases them, it grows for the entire running time of the application. - Captive Dependency - the most classic interview mistake: a Singleton should not depend on a Scoped or a stateful Transient. If a Singleton injects a Scoped service in its constructor, that Scoped service becomes "captive" and lives as long as the Singleton - so in practice it stops being Scoped. Most DI containers (including Microsoft.Extensions.DependencyInjection) will detect this and throw an exception at startup in scope validation mode.

// Bug: Captive Dependency
services.AddSingleton<INotificationManager, NotificationManager>();
services.AddScoped<IUserContext, UserContext>();

public class NotificationManager : INotificationManager
{
    // BUG: IUserContext (Scoped) will be "frozen" for the lifetime of the Singleton
    public NotificationManager(IUserContext userContext) { ... }
}

The solution: inject IServiceScopeFactory into the Singleton and create a scope manually when you actually need a Scoped dependency.

Comparison table

Transient Scoped Singleton
New instance Every time Once per scope Once per application
Thread-safety required? Usually not Usually not (one scope = one thread/request) Yes, mandatory
Typical example Validator, mapper DbContext, request context Cache, configuration, HTTP client
Biggest pitfall Wasting resources when creation is expensive Use outside a scope Captive dependency, lack of thread-safety

A question they may ask you in an interview

"What happens if a Singleton injects a Transient?" - That is OK, but with a caveat: this Transient object also effectively becomes a singleton, because the Singleton creates it once in its constructor and keeps the same reference for the whole life of the application. There is no technical error here (unlike a Scoped in a Singleton), but you have to be aware of the consequences if that Transient was supposed to be "fresh" on every use.


In the context of WPF: since there is no concept of a "request" there like in ASP.NET Core, Scoped makes sense mainly if you create scopes yourself (e.g. one per open window/dialog, or per operation such as "file import"). In simpler desktop applications, Singleton + Transient is often enough.

More pitfalls (ValidateScopes, DbContext and threads, registration forwarding, keyed services) are in the topic DI: lifetimes and pitfalls.

Buy me a coffee