📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you implement a thread-safe Singleton in C#? Compare a static readonly field, Lazy<T> and double-checked locking, and explain why in an ASP.NET Core app you would normally register a singleton in DI instead.

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.

Junior Theory Intermediate dependency-injection design-patterns lazy-initialisation singleton thread-safety

🎯 Key points

  • Singleton ensures one instance and a global access point; the GoF version uses a private constructor and a static Instance property
  • static readonly field: the CLR runs the type initialiser once and thread-safely; beforefieldinit means it may run earlier unless the class has an explicit static constructor
  • Lazy<T> defaults to LazyThreadSafetyMode.ExecutionAndPublication: the factory runs once, on first .Value, and exceptions are cached
  • Double-checked locking needs a volatile field (or Volatile.Read/Write) to be correct on weak memory models such as Arm64; Lazy<T> is simpler and correct
  • Hand-rolled singletons hide dependencies, make unit tests share state and can't be swapped for a fake
  • services.AddSingleton<T>() gives one instance per container, constructor injection, disposal of IDisposable instances it created, and test replacement
  • A DI singleton must be thread-safe and must not depend on scoped services (captive dependency)
  • A DI singleton is per container, not per process: two hosts or two WebApplicationFactory instances give two instances

⏱ 30-second answer

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.
  • Double-checked locking: it's only correct with a 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.

🗣 Full answer (senior)

How I would answer this in an interview

"Singleton means exactly one instance and one way to reach it. The classic C# version has a private constructor and a static Instance property, and there are three thread-safe ways to back it. The simplest is a static readonly field. 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 marked beforefieldinit, so the runtime may initialise it earlier than first use. The second option is Lazy<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 is volatile, because on weak memory models like Arm64 another thread could otherwise see a reference to a half-constructed object. Since Lazy<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's IDisposable, and lets tests swap in a fake. A static Instance hides 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."


The three implementations

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

Hand-rolled vs DI singleton

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

What "thread-safe" means for a DI singleton

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

Production example

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.

🔍 What the interviewer is checking

Checks basic concurrency awareness and whether the candidate knows that DI lifetimes replaced the hand-rolled pattern in modern .NET.

Green flags

  • Explains why the naive check races.
  • Knows Lazy<T> and the type-initialiser guarantee, and why double-checked locking needs volatile.
  • Says they would use AddSingleton and explains testability.
  • Mentions thread safety of the singleton's state and the scoped-dependency trap.

Red flags

  • Writes the naive version and calls it thread-safe.
  • Thinks a singleton only needs a thread-safe constructor, not thread-safe state.
  • Uses static singletons for services that need configuration or dependencies.

📚 Learn in depth

1. Structure

┌─────────────────────────────┐
│ 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.

2. Why static readonly is thread-safe

The 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.

3. 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.

4. Double-checked locking and the memory model

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.

5. How the DI container implements singletons

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.

6. Variations

  • Per-thread singleton: ThreadLocal<T> or [ThreadStatic]. Dangerous with async, because continuations change threads; AsyncLocal<T> flows with the async context instead.
  • Multiton: one instance per key, e.g. named options or keyed services (AddKeyedSingleton).
  • Monostate: many instances sharing static state. It is a code smell in modern .NET.

Try it yourself

  1. Write a naive singleton with a Thread.Sleep(10) in the constructor, call Instance from Parallel.For(0, 100, ...) and count constructor calls.
  2. Make a Lazy<T> factory throw once, then succeed; observe that .Value keeps throwing. Switch to PublicationOnly and compare.
  3. Register a singleton that injects a scoped service and run in Development; read the ValidateOnBuild error.
  4. Use two WebApplicationFactory<Program> instances in a test and show that the "singleton" exists twice.

💻 Code

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

⚠ Common mistakes

  • Mistake: The naive 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.
  • Mistake: Double-checked locking without 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>.
  • Mistake: Writing 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.
  • Mistake: Giving a singleton mutable, unsynchronised state such as a 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.
  • Mistake: Injecting a scoped service (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.
  • Mistake: Assuming a DI singleton is unique per process. Why it is wrong: Each 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.
  • Mistake: Registering an instance with 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.

🏛 Senior insight: trade-offs

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).

🔗 Follow-ups the interviewer may ask

  1. When: Candidate writes double-checked locking with lock Why: Checks how lock works and the .NET 9 Lock type
    How to answer

    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.

  2. When: Candidate uses a static readonly field Why: Checks static readonly versus const and what readonly does not guarantee
    How to answer

    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.

  3. When: Candidate says a DI singleton must not capture scoped services Why: Checks the captive-dependency failure that DI singletons cause
    How to answer

    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.

↩ Usually asked after

More in Creational Patterns

Last updated 18 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me