Singleton intent, three thread-safe C# implementations (static readonly with type initialiser guarantees, Lazy<T> with ExecutionAndPublication, double-checked locking with volatile), their pitfalls, and why the DI singleton lifetime replaces the hand-rolled pattern.
Singleton guarantees one instance with a global access point. In C# there are three thread-safe ways to write it:
static readonly field: the CLR runs the type initialiser once and thread-safely, so there's no lock to write. Without an explicit static constructor, the runtime may run that initialiser before first use (beforefieldinit), so add one if you need it to happen exactly on first access.Lazy<T>: the factory runs once on first .Value (ExecutionAndPublication by default). It's lazy and correct, which makes it the best choice for an expensive resource that may never be used. The catch is that a failed factory's exception is cached, so a transient failure stays broken until restart.volatile field. It's easy to get wrong, so prefer Lazy<T>.In ASP.NET Core I use services.AddSingleton<T>() instead. It gives one instance per container, constructor injection, disposal of what the container created, and a fake in tests. A static instance is still fine for truly stateless helpers like StringComparer.Ordinal. The trade-off is the same for both: a singleton is shared by every request, so it must be thread-safe and must never capture scoped services.
"Singleton means exactly one instance and one way to reach it. The classic C# version has a private constructor and a static
Instanceproperty, and there are three thread-safe ways to back it. The simplest is astatic readonlyfield. The CLR guarantees that a type initialiser runs once and is thread-safe, so there's no lock to write. The catch is laziness: without an explicit static constructor the class is markedbeforefieldinit, so the runtime may initialise it earlier than first use. The second option isLazy<T>. Its default mode,ExecutionAndPublication, runs the factory exactly once on first.Value, even under contention. One gotcha is that if the factory throws, that exception is cached and rethrown on every access. The third is double-checked locking: check, lock, check again, create. It's only correct if the field isvolatile, because on weak memory models like Arm64 another thread could otherwise see a reference to a half-constructed object. SinceLazy<T>already does this correctly, I don't hand-write it.In an ASP.NET Core app I almost never write any of these. I register the class with
AddSingleton<T>(). The container creates one instance per container, injects its dependencies through the constructor, disposes it at shutdown if it'sIDisposable, and lets tests swap in a fake. A staticInstancehides the dependency, shares state between tests and can't be replaced.The mistake I see is forgetting what 'singleton' implies: every request shares the object at the same time. So it must be thread-safe, which means immutable state, concurrent collections or locks, and it must never hold a scoped service like a
DbContext. The pattern is fine; the static access point is the part DI replaced."
| Approach | Thread-safe | Lazy | Exceptions | Verdict |
|---|---|---|---|---|
static readonly field |
Yes (type initialiser lock) | Only with an explicit static constructor | A throwing initialiser makes the type unusable (TypeInitializationException forever) |
Fine for cheap objects |
Lazy<T> |
Yes (ExecutionAndPublication) |
Yes | Cached and rethrown on every .Value |
Best hand-rolled option |
| Double-checked locking | Only with volatile |
Yes | Retries next call | Avoid; use Lazy<T> |
Naive if (_instance == null) _instance = new() |
No | Yes | — | Race: two instances |
| Concern | Static Instance |
AddSingleton<T>() |
|---|---|---|
| Dependencies | Hidden (calls other statics) | Visible in constructor |
| Tests | Shared state, can't fake | Replace registration per test |
| Disposal | Never | Container disposes instances it created |
| Scope | Per process (per AppDomain/ALC) | Per container |
| Configuration | Hard-coded | IOptions<T> injected |
| State kind | Safe? | Fix if not |
|---|---|---|
| Immutable fields set in constructor | Yes | — |
Dictionary<K,V> written by requests |
No | ConcurrentDictionary, FrozenDictionary for read-only, or a lock |
Counter _count++ |
No | Interlocked.Increment |
A captured DbContext or HttpContext |
No (and wrong lifetime) | Inject IServiceScopeFactory or IHttpContextAccessor, or change lifetime |
A pricing service had a hand-rolled PriceCache.Instance with a plain Dictionary. Under load (around 1,200 requests per second) concurrent writes corrupted the dictionary's buckets and threads spun at 100% CPU in FindValue. We replaced it with an AddSingleton<IPriceCache> backed by ConcurrentDictionary, injected TimeProvider for expiry, and covered it with a parallel test. CPU dropped back to about 35% and the hangs stopped.
Checks basic concurrency awareness and whether the candidate knows that DI lifetimes replaced the hand-rolled pattern in modern .NET.
Green flags
Lazy<T> and the type-initialiser guarantee, and why double-checked locking needs volatile.AddSingleton and explains testability.Red flags
┌─────────────────────────────┐
│ Singleton │
├─────────────────────────────┤
│ - static instance │
│ - Singleton() (private) │
├─────────────────────────────┤
│ + static Instance { get; } │
└─────────────────────────────┘
▲
│ every caller uses Singleton.Instance
Two responsibilities are bundled together: controlling the number of instances and providing global access. DI keeps the first and replaces the second with constructor injection.
static readonly is thread-safeThe CLR runs a type's static initialiser (.cctor) at most once per type per AppDomain (per assembly load context in .NET). It takes an internal lock while running it, so concurrent first accesses wait. If the class has no explicit static constructor, the C# compiler marks it beforefieldinit, which allows the runtime to run the initialiser at any time before the first static field access, possibly earlier. Adding an empty static Singleton() { } removes beforefieldinit and makes initialisation happen exactly at first access. In practice modern .NET initialises lazily either way, but the explicit constructor is the documented guarantee.
If the initialiser throws, the type is broken for the life of the process: every access throws TypeInitializationException.
Lazy<T> modes| Mode | Behaviour |
|---|---|
ExecutionAndPublication (default with a factory) |
Lock; factory runs once; exceptions cached |
PublicationOnly |
Factory may run on several threads; first result wins; exceptions not cached |
None |
No thread safety; fastest; single-threaded use only |
The exception caching matters: if the factory reads a config file that is briefly missing, every later access fails until restart. PublicationOnly retries but may create several instances.
if (_instance is null) // 1st check, no lock
{
lock (Gate)
{
_instance ??= new Singleton(); // 2nd check inside lock
}
}
return _instance;
Without volatile, the write of the reference could become visible to another core before the constructor's field writes. That core passes the first check and uses a half-initialised object. On x64 the strong memory model hides this; on Arm64 (Graviton, Ampere, Apple Silicon) it can really happen. volatile (or Volatile.Write on publish and Volatile.Read on check) adds the release/acquire ordering.
ServiceProvider caches singleton instances in the root scope. The first resolution builds the instance (taking a lock per service), and later resolutions return the cached object. At shutdown, disposing the root provider calls Dispose/DisposeAsync on singletons it created, but not on instances you passed in with AddSingleton(instance). In Development, the host sets ValidateScopes and ValidateOnBuild, which catch a singleton depending on a scoped service.
ThreadLocal<T> or [ThreadStatic]. Dangerous with async, because continuations change threads; AsyncLocal<T> flows with the async context instead.AddKeyedSingleton).Thread.Sleep(10) in the constructor, call Instance from Parallel.For(0, 100, ...) and count constructor calls.Lazy<T> factory throw once, then succeed; observe that .Value keeps throwing. Switch to PublicationOnly and compare.ValidateOnBuild error.WebApplicationFactory<Program> instances in a test and show that the "singleton" exists twice.Hand-rolled options, then the DI version you would actually ship:
namespace Singletons;
// 1. static readonly: thread-safe via the type initialiser
public sealed class Clock1
{
public static Clock1 Instance { get; } = new();
static Clock1() { } // removes beforefieldinit: initialise exactly on first access
private Clock1() { }
}
// 2. Lazy<T>: lazy, thread-safe, but caches exceptions from the factory
public sealed class Clock2
{
private static readonly Lazy<Clock2> LazyInstance = new(() => new Clock2());
public static Clock2 Instance => LazyInstance.Value;
private Clock2() { }
}
// 3. Double-checked locking: only correct because of volatile. Prefer Lazy<T>.
public sealed class Clock3
{
private static volatile Clock3? _instance;
private static readonly Lock Gate = new(); // System.Threading.Lock (.NET 9+)
public static Clock3 Instance
{
get
{
if (_instance is null)
{
lock (Gate)
{
_instance ??= new Clock3();
}
}
return _instance;
}
}
private Clock3() { }
}
// What you ship: a normal class, thread-safe, with one instance managed by the container
namespace Pricing;
using System.Collections.Concurrent;
public interface IPriceCache
{
bool TryGet(string sku, out decimal price);
void Set(string sku, decimal price);
}
public sealed class PriceCache(TimeProvider time) : IPriceCache
{
private readonly ConcurrentDictionary<string, (decimal Price, DateTimeOffset Expires)> _items = new();
public bool TryGet(string sku, out decimal price)
{
if (_items.TryGetValue(sku, out var e) && e.Expires > time.GetUtcNow())
{
price = e.Price;
return true;
}
price = 0;
return false;
}
public void Set(string sku, decimal price) =>
_items[sku] = (price, time.GetUtcNow().AddMinutes(5));
}
// Program.cs
// builder.Services.AddSingleton(TimeProvider.System);
// builder.Services.AddSingleton<IPriceCache, PriceCache>(); // one per container, injectable, fakeable
if (_instance == null) _instance = new() check. Why it is wrong: Two threads can both see null and create two instances; any state in the first is lost. Instead: Use static readonly, Lazy<T> or DI.volatile. Why it is wrong: On Arm64 another thread can observe the reference before the constructor's writes, and use a half-built object. Instead: Mark the field volatile, or just use Lazy<T>.Foo.Instance in an ASP.NET Core app. Why it is wrong: It hides the dependency, makes tests share state and can't be faked or configured with IOptions<T>. Instead: AddSingleton<IFoo, Foo>() and constructor injection.Dictionary or List. Why it is wrong: Concurrent requests corrupt it; a corrupted Dictionary can spin threads at 100% CPU. Instead: Immutable state, ConcurrentDictionary, FrozenDictionary for read-only data, or a lock.DbContext) into a singleton. Why it is wrong: It becomes a captive dependency shared across requests and is not thread-safe. Instead: Inject IServiceScopeFactory and create a scope per operation, or make the consumer scoped.ServiceProvider has its own; integration tests with two factories, or two hosts, get two instances. Instead: Don't rely on singletons for cross-process uniqueness; use a distributed lock or the database.AddSingleton(new Foo()) and expecting the container to dispose it. Why it is wrong: The container only disposes services it created. Instead: Use AddSingleton<Foo>() or a factory, or dispose it yourself on shutdown.The GoF Singleton bundles two things: one instance (a lifetime decision) and global access (a dependency decision). Modern .NET keeps the first and rejects the second. The container owns lifetimes, and constructor injection makes dependencies visible. I treat every static Instance in an application codebase as a review comment, except for genuinely stateless helpers or framework-style singletons like TimeProvider.System and ArrayPool<T>.Shared, which are designed for it.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
AddSingleton<T>() |
Stateless or thread-safe shared services, caches, clients | Must be thread-safe; no scoped deps | Per-request or per-user state |
static readonly field |
Library-level immutable defaults (Comparer, JsonSerializerOptions) |
Not replaceable in tests | Anything with dependencies or configuration |
Lazy<T> |
Expensive, rarely used resource in a library | Exception caching | When DI is available |
| Scoped instead | Anything touching DbContext, user or tenant |
One per request | Expensive objects needed by background work |
To prove a singleton is safe, I run a parallel stress test (Parallel.ForEachAsync with 1,000 calls) and watch for exceptions and wrong counts. In production I use dotnet-counters for CPU and lock contention (monitor-lock-contention-count).
lock (x) { ... } gives mutual exclusion: only one thread at a time runs the block for the same lock object, and entering and leaving act as memory barriers. For a normal object the compiler emits Monitor.Enter(x, ref lockTaken) in a try/finally with Monitor.Exit. Since .NET 9 and C# 13, if x is a System.Threading.Lock, the compiler instead uses x.EnterScope() and disposes the scope, which is a dedicated, slightly faster lock type. Locks are re-entrant on the same thread, you cannot await inside one (CS1996), and you should lock on a private, readonly object and keep the block short.
readonly always means "this storage cannot be reassigned after initialisation", but the scope differs. A readonly field can be set only in its initialiser or a constructor (or an init accessor). const is a compile-time literal copied into every caller, so changing it in a library does nothing until callers recompile; static readonly is read at run time, and the tiered JIT treats it as a constant once initialised, so it is just as fast for primitives. A readonly struct has only readonly fields, and readonly members (C# 8) promise not to mutate this, which removes defensive copies. ref readonly returns give a reference callers cannot write through. None of these make referenced objects immutable: a readonly List<T> can still be added to.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
Last updated 18 Nov 2026.