S Singleton Pattern
/
GoF · Creational Pattern

One instance.
Everyone agrees on the guarantee.
Almost no one agrees on the cost.

Singleton is the shortest description in the Gang of Four book and the most argued-about pattern in the catalog. This guide builds it properly in C# 14 / .NET 10 — Lazy<T>, System.Threading.Lock, and the DI-singleton-lifetime alternative — and gives the anti-pattern case its full due rather than a footnote.

17 sections 15 diagrams 19 C# samples ~24 min read
1
Scroll to explore
1

TL;DR — Intent and the Core Trade-off

Singleton guarantees that a class has exactly one instance for the lifetime of a process, and hands out a single, well-known way to reach it. That's the whole pattern. The GoF book states it as ensuring a class only ever produces one object and giving the rest of the program a single point of access to that object — everything else is implementation detail around those two clauses.

The one rule that defines it: construction is forbidden to everyone except the class itself, and every caller who asks for an instance gets the same one back. If two calls to a "singleton" can ever return different objects, it isn't one — it's a factory with a cache, which is a different (and often better) thing.

What you buy: a single shared point of coordination — one connection pool, one cache, one clock — reachable from anywhere without threading a reference through every constructor.

What you pay: global, mutable, hidden state. Every consumer becomes implicitly coupled to every other consumer through that shared instance, tests can no longer isolate a unit without resetting or faking the global, and the "there will only ever be one" assumption is exactly the kind of assumption that stops being true the moment your architecture changes underneath it.

Nothing later in this document walks that trade-off back. Section 11 makes the "don't use it" case as sharp as the "use it" case, and Section 12 keeps the disagreement open rather than resolving it in the pattern's favor.

2

Origins, Classification, and the Problem It Solves

Singleton is a Creational pattern in the GoF taxonomy, and it operates at object scope — its constraint is about how many objects exist at runtime, not about which class the shape of an object belongs to. It first appears formally in Design Patterns: Elements of Reusable Object-Oriented Software (Gamma, Helm, Johnson, Vlissides — "the Gang of Four"), published in 1994, though the underlying idea — a module-level global with controlled construction — predates the book by decades in C and Smalltalk practice.

What it was reacting to in 1994-era C++: global variables with no construction-order guarantees, no encapsulation, and no way to defer expensive initialization. A raw global object is constructed whenever static-initialization order says so — which, across translation units, C++ famously does not fully define — and it's always live once the program starts, whether or not anything ever uses it. Singleton fixed both problems at once: initialization happens lazily on first request, inside a method the class controls, and the "only one" guarantee is enforced by the type rather than by programmer discipline.

The actual pain it targets, in terms a working C# developer recognizes immediately, looks like this:

C#
// Config/AppConfig.cs — "before": a new AppConfig() at every call site
public class AppConfig
{
    public string ConnectionString { get; }
    public int MaxRetries { get; }

    public AppConfig()
    {
        // Re-reads and re-parses appsettings.json on EVERY construction.
        var json = File.ReadAllText("appsettings.json");
        var doc = JsonDocument.Parse(json);
        ConnectionString = doc.RootElement.GetProperty("ConnectionString").GetString()!;
        MaxRetries = doc.RootElement.GetProperty("MaxRetries").GetInt32();
    }
}

// Scattered across 40 files like this:
public class OrderProcessor
{
    private readonly AppConfig _config = new AppConfig(); // re-parses the file, again
    public void Process(Order o)
    {
        for (int i = 0; i < _config.MaxRetries; i++) { /* ... */ }
    }
}

public class ReportExporter
{
    private readonly AppConfig _config = new AppConfig(); // and again
}
// Every new AppConfig() re-reads disk. Nobody agrees on when the file is
// re-read. A hotfix to the connection string mid-run behaves differently
// depending on which object asks for it first.

This is the shape of code Singleton exists to remove: a piece of state that is genuinely one-per-process (parsed configuration, a hardware handle, a connection pool) but is re-constructed at every call site because nothing enforces otherwise — expensive, inconsistent, and impossible to reason about under concurrent access.

The problem — forty call sites, forty re-parses
flowchart TD F[("appsettings.json
on disk")] OP["OrderProcessor"] -- "new AppConfig()" --> F RE["ReportExporter"] -- "new AppConfig()" --> F NF["NotificationSender"] -- "new AppConfig()" --> F ETC["...37 more call sites"] -- "new AppConfig()" --> F
3

Structure and Participants

Singleton's structure is the smallest in the catalog — one class, one static accessor, one private field.

Canonical Singleton structure
classDiagram class Singleton { -static Singleton _instance -Singleton() +static Singleton Instance +DoWork() void } note for Singleton "Constructor is private.
Instance is the only path in."
ParticipantRoleBelongs in itMust never be in it
SingletonOwns its own single instance and exposes the access pointThe private constructor, the static holder field, the accessor, the actual behaviour clients wantA public constructor; any second way to obtain an instance
Static accessor (Instance)The single, well-known path every caller usesLazy creation logic, thread-safety guardBusiness logic — it should do nothing but hand back the instance
ClientAnything that calls Singleton.InstanceCalls, nothing elseIts own cached reference held past the call that would let it silently diverge from the real instance

The membership test: a class is genuinely a Singleton — not just a class you happen to construct once — if and only if its constructor is inaccessible from outside and the type itself is the thing enforcing "exactly one," not a convention, a comment, or a DI container configuration. If construction is public and callers simply agree not to call it twice, that's not Singleton; that's hope.

4

The Central Mechanic

The single structural trick is this: the class hides its own constructor from everyone and hands out the same pre-built (or lazily-built) instance through a static member it fully controls. There is no interface, no polymorphism, no second object collaborating — the "pattern" is entirely inside one class's control over its own lifecycle.

The mechanic — construction gate plus static holder
flowchart LR A["Caller A calls
Singleton.Instance"] --> G{"Has _instance
been created?"} B["Caller B calls
Singleton.Instance"] --> G G -- "no, first caller" --> C["new Singleton()
via private ctor"] C --> H["_instance stored"] G -- "yes" --> H H --> R["Same reference
returned to A and B"]
C#
// The mechanic, stripped to its smallest possible form.
public sealed class Singleton
{
    private static Singleton? _instance;
    private Singleton() { }                 // 1. construction gated

    public static Singleton Instance =>      // 2. one well-known path
        _instance ??= new Singleton();       // 3. same reference every time
}

Everything the rest of this document discusses — thread safety, lifetime, testability, the DI alternative — is a variation on how step 3 is made safe and how step 2 is exposed. The mechanic itself never changes.

Step through — two threads racing on first access
Thread A caller Thread B caller Lock System.Threading.Lock _instance static field

5

Implementation in C# — Naive, Then Idiomatic

Pass one — the literal textbook translation

A deliberately literal port of the GoF structure: double-checked locking with the pre-2013 object lock, because that's what most tutorials still show.

C#
// ConnectionPool/NaiveConnectionPool.cs — literal GoF translation
public class NaiveConnectionPool
{
    private static NaiveConnectionPool _instance;
    private static readonly object _lock = new object();

    private NaiveConnectionPool()
    {
        Console.WriteLine("Reading connection settings from disk...");
    }

    public static NaiveConnectionPool GetInstance()
    {
        if (_instance == null)               // first check, outside the lock
        {
            lock (_lock)
            {
                if (_instance == null)       // second check, inside the lock
                {
                    _instance = new NaiveConnectionPool();
                }
            }
        }
        return _instance;
    }
}

It works, and double-checked locking here is not a myth — it correctly avoids taking the lock on every call once _instance is set. But it's verbose, it uses the pre-Lock synchronization type, it exposes a Java-style GetInstance() method instead of a property, and it has no nullable annotations telling the reader that _instance starts as null on purpose.

Pass two — what a .NET 10 developer actually writes in 2026

C#
// ConnectionPool/ConnectionPool.cs — idiomatic .NET 10 / C# 14
public sealed class ConnectionPool
{
    private static readonly Lazy<ConnectionPool> _lazy =
        new(() => new ConnectionPool(), LazyThreadSafetyMode.ExecutionAndPublication);

    public static ConnectionPool Instance => _lazy.Value;

    private readonly string _connectionString;

    private ConnectionPool()
    {
        _connectionString = LoadConnectionStringFromDisk();
    }

    public NpgsqlConnection Rent() => new(_connectionString);

    private static string LoadConnectionStringFromDisk() =>
        File.ReadAllText("connection-string.secret");
}

What changed and why it's better here specifically, not as generic style advice:

  • sealed by default: an unsealed Singleton lets a subclass introduce a second constructible type, quietly breaking the "exactly one" guarantee the whole pattern exists to enforce.
  • Lazy<T> instead of hand-rolled double-checked locking: the BCL has already solved this race correctly, including the subtle bit where the initializer delegate itself must not run twice under ExecutionAndPublication. Hand-rolling it is re-solving a solved problem with more surface area for a mistake.
  • A property, not a GetInstance() method: retrieving an existing value is a property in C# idiom; a method name signals an action, and there's no action here beyond field access.
  • No public parameterless constructor, ever: the naive version already got this right, and the idiomatic version keeps it — this is the one piece of ceremony that isn't optional.
6

Variations and Modern .NET Idioms

VariationWhen it fitsTrade-off
Lazy<T> holderGeneral case; construction has any real cost or can throwDeferred creation, thread-safe by construction, one extra allocation for the Lazy<T> wrapper itself
Static field initializer (= new())Construction is cheap, side-effect-free, and can't failThe CLR guarantees this runs before first use of the type — but "first use of the type" includes any static member access, which can surprise people; no explicit laziness control
static readonly + explicit static constructorYou need to control exactly when the type initializer runs relative to other staticsMore ceremony for a guarantee Lazy<T> already gives you in the common case
DI singleton lifetime (AddSingleton)ASP.NET Core / generic host apps — almost always the right default todayNot a GoF Singleton at all: construction is public, the container owns lifetime, and the "one instance" guarantee is a configuration choice, not a type-level one — see §12

The honest observation: in a DI-first .NET codebase, the classic static-accessor Singleton has been substantially absorbed by container-managed singleton lifetime. If a container is already wired through the app, reaching for the GoF form specifically to get "one instance" is usually solving a problem the container already solves, with worse testability. The GoF form still earns its place for things that must exist before or independent of any container — a process-wide static logger bootstrap, a native handle wrapper, a pattern-catalog reference implementation like this one.

C#
// ConnectionPool/ThreadSafeLockPool.cs — variation using System.Threading.Lock
// directly (C# 13+), for the case where you want explicit control over the
// critical section rather than delegating entirely to Lazy<T>.
public sealed class ThreadSafeLockPool
{
    private static ThreadSafeLockPool? _instance;
    private static readonly Lock _gate = new();

    public static ThreadSafeLockPool Instance
    {
        get
        {
            if (_instance is not null) return _instance;
            using (_gate.EnterScope())
            {
                return _instance ??= new ThreadSafeLockPool();
            }
        }
    }

    private ThreadSafeLockPool() { }
}

The DI-managed relative, registered the way a real ASP.NET Core app would — no static accessor anywhere, construction is public and ordinary, and the container owns lifetime and disposal:

C#
// Program.cs — the DI-native alternative to the static accessor form
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton<IConnectionPool, ConnectionPoolService>();

var app = builder.Build();
app.MapGet("/orders", (IConnectionPool pool) => pool.Rent());
app.Run();

// ConnectionPool/ConnectionPoolService.cs — public constructor, no static Instance
public sealed class ConnectionPoolService : IConnectionPool
{
    private readonly string _connectionString;
    public ConnectionPoolService(IConfiguration config) =>
        _connectionString = config.GetConnectionString("Default")!;

    public NpgsqlConnection Rent() => new(_connectionString);
}
// A test can new up ConnectionPoolService directly with a fake IConfiguration —
// no static state to reset, no shared process-wide instance across test classes.
7

Where .NET Itself Uses It

Genuine, verified instances of the one-instance idea inside the BCL and ASP.NET Core — some textbook Singleton, some the DI-managed relative:

Type / memberHow it maps
Comparer<T>.DefaultStatic accessor guarding a per-type cached default comparer — textbook shape, generic-parameterized
Encoding.UTF8 / Encoding.ASCIIStatic properties returning shared, immutable instances rather than constructing per call
CultureInfo.InvariantCultureA single immutable instance handed out through a static property, exactly the accessor shape from §4
HttpClient (as commonly deployed via IHttpClientFactory)Not itself a Singleton type, but the guidance to reuse one HttpClient (or one per named client) for socket-pooling reasons is the same "expensive shared resource, one instance" motivation Singleton targets
ASP.NET Core DI singleton lifetime (services.AddSingleton<T>())The container-managed relative — worth flagging as the one that has mostly replaced the classic form in web apps, and the one that raises the controversial "is IServiceProvider resolution itself a Service Locator" question (see §12)
C#
// Direct use of a real BCL "one shared instance" accessor.
var invariant = CultureInfo.InvariantCulture;
var sameOne   = CultureInfo.InvariantCulture;
Console.WriteLine(ReferenceEquals(invariant, sameOne)); // True — same object, every call

var comparer = Comparer<int>.Default;
Console.WriteLine(ReferenceEquals(comparer, Comparer<int>.Default)); // True
8

Runtime Flows

Happy path — first access, then every access after

Happy path — lazy creation on first call only
sequenceDiagram participant C1 as Caller (1st) participant S as ConnectionPool.Instance participant L as Lazy<T> C1->>S: Instance S->>L: .Value L->>L: construct once L-->>S: instance S-->>C1: instance participant C2 as Caller (2nd) C2->>S: Instance S->>L: .Value L-->>S: cached instance (no construction) S-->>C2: instance

Failure path — construction throws

Failure path — the exception is cached, not just rethrown
sequenceDiagram participant C1 as Caller (1st) participant S as Singleton.Instance participant L as Lazy<T> (default mode) C1->>S: Instance S->>L: .Value L->>L: constructor throws IOException L-->>S: rethrows IOException S-->>C1: IOException propagates participant C2 as Caller (2nd) C2->>S: Instance S->>L: .Value L-->>S: rethrows the SAME cached exception S-->>C2: IOException propagates again, forever

This is a genuinely surprising edge with Lazy<T>'s default mode: once the initializer throws, every subsequent access re-throws the cached exception rather than retrying — the type is permanently faulted for the process lifetime. If a transient failure (a config file briefly locked by another process) should be retryable, that needs an explicit retry wrapper around the Lazy<T>, not a hope that the default mode will recover.

Structurally interesting path — lifetime versus process-restart assumptions

The assumption breaking — one process becomes many
sequenceDiagram participant W1 as Worker process 1 participant S1 as Singleton (in W1) participant W2 as Worker process 2 participant S2 as Singleton (in W2) W1->>S1: Instance S1-->>W1: instance A (in-memory counter = 0) W2->>S2: Instance S2-->>W2: instance B (in-memory counter = 0) Note over S1,S2: Each process has its OWN "the one instance" —
the singleton guarantee never spanned processes to begin with. W1->>S1: Increment() S1-->>W1: counter = 1 W2->>S2: Increment() S2-->>W2: counter = 1, NOT 2
9

Real-World Worked Examples — Three

1. Feature-flag snapshot cache (a clean fit)

A feature-flag service polls a remote source every 30 seconds and needs exactly one in-memory snapshot that every request handler reads without re-fetching. There's no per-request variation to model — the snapshot really is process-global.

C#
// FeatureFlags/FeatureFlagSnapshot.cs
public sealed class FeatureFlagSnapshot
{
    private static readonly Lazy<FeatureFlagSnapshot> _lazy = new(() => new());
    public static FeatureFlagSnapshot Instance => _lazy.Value;

    private volatile ImmutableDictionary<string, bool> _flags =
        ImmutableDictionary<string, bool>.Empty;

    private FeatureFlagSnapshot() { }

    public bool IsEnabled(string flag) => _flags.TryGetValue(flag, out var on) && on;

    // Called by a background IHostedService every 30s — replaces the whole
    // dictionary atomically rather than mutating it in place.
    public void ReplaceSnapshot(ImmutableDictionary<string, bool> next) => _flags = next;
}
Feature-flag snapshot — many readers, one writer
flowchart LR P["Poller (IHostedService)"] -- "ReplaceSnapshot()
every 30s" --> F["FeatureFlagSnapshot.Instance"] R1["Request handler 1"] -- "IsEnabled()" --> F R2["Request handler 2"] -- "IsEnabled()" --> F R3["Request handler 3"] -- "IsEnabled()" --> F

2. Retry/resilience circuit-breaker registry (an uncomfortable fit)

A team wants one shared circuit-breaker state per downstream dependency, reachable from anywhere in the codebase without threading it through every call. The instinct is a Singleton registry — but circuit-breaker state is exactly the kind of thing that should be scoped to one HTTP client configuration, and .NET already has a first-class home for it: Microsoft.Extensions.Http.Resilience registered per named/typed client. Building a hand-rolled Singleton registry duplicates infrastructure the framework already owns and makes the breaker state invisible to the DI container's own lifecycle and disposal.

C#
// ❌ The uncomfortable fit: a hand-rolled Singleton registry
public sealed class CircuitBreakerRegistry
{
    private static readonly Lazy<CircuitBreakerRegistry> _lazy = new(() => new());
    public static CircuitBreakerRegistry Instance => _lazy.Value;

    private readonly ConcurrentDictionary<string, bool> _open = new();
    private CircuitBreakerRegistry() { }

    public bool IsOpen(string dependency) => _open.GetValueOrDefault(dependency);
    public void Trip(string dependency) => _open[dependency] = true;
}
// Works, but: invisible to DI, invisible to the app's shutdown/disposal
// sequence, and duplicates functionality Polly/Microsoft.Extensions.Http.Resilience
// already provides per named HttpClient — with none of this code.

The honest note for this example: it's included specifically because it's the kind of "obviously global, so obviously Singleton" case that turns out to be a worse fit than a framework-provided alternative once you look one layer deeper.

Circuit breaker — hand-rolled registry vs framework home
flowchart LR C["Caller"] --> HR["CircuitBreakerRegistry.Instance
(hand-rolled, invisible to DI)"] C2["Caller"] --> RH["Named HttpClient +
Microsoft.Extensions.Http.Resilience
(framework-owned, disposable)"]

3. Audit-log sink for a batch export job (a clean fit, with an explicit lifetime boundary)

A nightly export job writes audit records to a single append-only file handle that must not be opened twice — the OS file lock would reject a second writer. One process, one job run, one file handle — genuinely one-per-process-lifetime.

C#
// AuditLog/AuditLogSink.cs
public sealed class AuditLogSink : IDisposable
{
    private static readonly Lazy<AuditLogSink> _lazy = new(() => new());
    public static AuditLogSink Instance => _lazy.Value;

    private readonly StreamWriter _writer;
    private readonly Lock _gate = new();

    private AuditLogSink()
    {
        _writer = new StreamWriter(
            new FileStream("audit.log", FileMode.Append, FileAccess.Write, FileShare.None));
    }

    public async Task WriteAsync(string entry)
    {
        using (_gate.EnterScope())
        {
            await _writer.WriteLineAsync($"{DateTimeOffset.UtcNow:O} {entry}");
        }
    }

    public void Dispose() => _writer.Dispose();
}
Audit sink — one file handle, many writers
flowchart LR J1["Export task: Customers"] --> A["AuditLogSink.Instance"] J2["Export task: Orders"] --> A J3["Export task: Invoices"] --> A A --> F[("audit.log
single FileStream, FileShare.None")]
10

Testing Code That Uses It

Singleton's testing pain is specific and well-known: static state leaks across test methods. Two tests in the same run share the same process, so they share the same _lazy.Value — a test that mutates the singleton's state pollutes every test that runs after it, and xUnit's default parallel test execution turns that pollution into flaky, order-dependent failures rather than a deterministic bug.

C#
// ❌ Flaky: depends on test execution order and shared process state
public class FeatureFlagSnapshotTests
{
    [Fact]
    public void IsEnabled_ReturnsFalse_WhenFlagAbsent()
    {
        // FeatureFlagSnapshot.Instance may already have flags set by an
        // earlier test in the same test run — this assertion is not isolated.
        Assert.False(FeatureFlagSnapshot.Instance.IsEnabled("new-checkout"));
    }
}

// ✅ Isolated: the singleton exposes an internal reset seam for tests, and the
// test collection disables parallelization for anything touching it.
[CollectionDefinition("SingletonState", DisableParallelization = true)]
public class SingletonStateCollection { }

[Collection("SingletonState")]
public class FeatureFlagSnapshotTests
{
    public FeatureFlagSnapshotTests()
    {
        FeatureFlagSnapshot.Instance.ReplaceSnapshot(ImmutableDictionary<string, bool>.Empty);
    }

    [Fact]
    public void IsEnabled_ReturnsFalse_WhenFlagAbsent()
    {
        Assert.False(FeatureFlagSnapshot.Instance.IsEnabled("new-checkout"));
    }

    [Fact]
    public void IsEnabled_ReturnsTrue_AfterReplaceSnapshot()
    {
        var flags = ImmutableDictionary<string, bool>.Empty.SetItem("new-checkout", true);
        FeatureFlagSnapshot.Instance.ReplaceSnapshot(flags);
        Assert.True(FeatureFlagSnapshot.Instance.IsEnabled("new-checkout"));
    }
}

An integration-level test on the audit sink, verifying the file-lock guarantee the Singleton exists to enforce rather than mocking it away:

C#
[Collection("SingletonState")]
public class AuditLogSinkIntegrationTests
{
    [Fact]
    public async Task ConcurrentWrites_AreSerialized_NoInterleavedLines()
    {
        var tasks = Enumerable.Range(0, 50)
            .Select(i => AuditLogSink.Instance.WriteAsync($"entry-{i}"));
        await Task.WhenAll(tasks);

        var lines = await File.ReadAllLinesAsync("audit.log");
        Assert.Equal(50, lines.Length);
        Assert.All(lines, l => Assert.Matches(@"^\d{4}-\d{2}-\d{2}T.*entry-\d+$", l));
    }
}

The general lesson: a Singleton that never exposes any reset or injection seam is untestable by construction. A Singleton that exposes one deliberate seam — a ReplaceSnapshot, an internal test-only reset, or an interface the type also happens to implement — stays testable without giving up the one-instance guarantee for production callers.

11

When To Use It — And When Not To

Decision tree — should this actually be a Singleton?
flowchart TD A["Does the resource have real,
process-wide shared state?"] -- "no" --> B["Use a normal class,
constructed where needed"] A -- "yes" --> C["Is a DI container already
wired through this app?"] C -- "yes" --> D["Use container singleton lifetime
(AddSingleton) — see §12"] C -- "no" --> E["Must it be reachable before
any container exists,
or truly framework-independent?"] E -- "no" --> D E -- "yes" --> F["Classic GoF Singleton is justified —
add a reset/injection seam for tests"]

Use it when:

  • The resource is genuinely one-per-process by the nature of the underlying thing — a file lock, a native OS handle, a hardware port — not by current architectural convenience.
  • No DI container is wired through the code path that needs it (a static utility library, a bootstrap-time logger before the host is built).
  • Construction is expensive enough that eager, repeated construction would be a measurable cost, and deferring it to first use has real value.

Don't use it when:

  • You have exactly one implementation today and no second one is plausible — that's just a class, not a pattern that needs a name.
  • A DI container is already present in the app; container singleton lifetime gives the same guarantee with a testable seam for free (§12).
  • The "only one" assumption has never actually been challenged — no multi-tenant requirement, no need for parallel test isolation, no plan to shard. If it's never been tested, it's not confirmed, it's just untested.
  • The indirection will be read by people six months from now who have never seen this document and will treat the static accessor as an ordinary dependency, not as global mutable state with the coupling that implies.
12

Pros and Cons, Honestly

ProsWhy it matters
Guaranteed single instanceEliminates an entire class of "which one is the real one" bugs for genuinely process-global resources
Lazy, controlled initializationExpensive setup happens once, on first demand, not at process start regardless of use
No constructor parameters to thread through call chainsReachable from anywhere without modifying every intermediate signature
ConsWhy it matters
Global mutable stateAny two unrelated pieces of code that touch the singleton are now implicitly coupled through it
Hidden dependencyA class calling Singleton.Instance internally doesn't declare that dependency in its constructor — it's invisible at the call site and in any dependency graph
Hard to test in isolationStatic state must be reset between tests, and parallel test runners actively fight this (§10)
Assumption fragility"Only one" is a claim about the future, and the future has a documented habit of introducing multi-tenancy, sharding, or parallelism that breaks it (§8's third flow)
Violates Single ResponsibilityThe class is responsible both for its actual behaviour and for enforcing its own cardinality — two reasons to change, bundled into one type

The cons list is longer here on purpose — this is one of the few patterns in the catalog where that's earned rather than an oversight.

The contested trade-off, stated as a genuine disagreement: is a container-managed singleton lifetime (AddSingleton<T>) actually a different, better thing than GoF Singleton — or is it the same design damage wearing a DI wrapper?

One side argues it's categorically different: construction is public, ordinary, and testable in isolation with a fresh container per test; the "one instance per app" guarantee is a runtime configuration choice the container owns, not a compile-time constraint baked into the type, so nothing stops a second container (in a test, in a plugin host) from having its own instance. The other side argues the difference is cosmetic: the object is still one process-wide mutable thing that every consumer implicitly shares once resolved, IServiceProvider itself functions as a service locator when injected directly rather than via constructor parameters, and swapping a static field for a container registration doesn't remove the coupling — it just moves who's holding the reference. Neither side is simply wrong; which one matters more depends on whether the team's actual pain has been "we can't test this" (container wins clearly) or "we don't know who depends on what" (the container argument is weaker, since IServiceProvider injection can hide dependencies just as effectively as a static accessor).

14

Common Mistakes and Anti-Patterns

Mistake 1 — a public constructor left "just in case"

C#
// ❌ "Singleton" with a public constructor — not actually one
public class Cache
{
    public static Cache Instance { get; } = new Cache();
    public Cache() { }   // public — anyone can `new Cache()` a second instance
}

// ✅ Constructor is private; Instance is the only path
public sealed class Cache
{
    public static Cache Instance { get; } = new();
    private Cache() { }
}

This compiles, passes any test that only exercises Cache.Instance, and quietly allows a second cache to exist the moment anyone — including a future maintainer who doesn't know the convention — calls new Cache() directly.

Public constructor — the guarantee silently breaks
flowchart LR A["Cache.Instance"] --> I1["Instance A"] B["new Cache()
(nobody stops this)"] --> I2["Instance B"] I1 -. "different objects,
diverging state" .- I2

Mistake 2 — a Singleton holding a scoped dependency

C#
// ❌ Compiles, passes early tests, corrupts data under real traffic
public sealed class RequestCache
{
    private static readonly Lazy<RequestCache> _lazy = new(() => new());
    public static RequestCache Instance => _lazy.Value;

    private AppDbContext? _db;   // captured once, reused across ALL requests
    private RequestCache() { }

    public void AttachContext(AppDbContext db) => _db = db;   // called per-request!
    public Customer GetCustomer(int id) => _db!.Customers.Find(id)!;
}
// Request A calls AttachContext with its DbContext. Request B, running
// concurrently, calls AttachContext with ITS DbContext, overwriting A's
// reference mid-flight. A now queries B's DbContext. Six months of "works
// on my machine" before this shows up under real concurrent load.

// ✅ The scoped dependency stays scoped; the singleton never holds it
public sealed class RequestCacheReader
{
    // No static instance holding EF state at all — inject AppDbContext
    // per-request the normal way, or make the "shared" part something that
    // is genuinely process-wide, like an in-memory read-through cache keyed
    // by id, with no reference to any one request's DbContext.
    private readonly IMemoryCache _cache;
    public RequestCacheReader(IMemoryCache cache) => _cache = cache;

    public Customer GetCustomer(int id, AppDbContext db) =>
        _cache.GetOrCreate(id, _ => db.Customers.Find(id)!)!;
}

This is the subtle one flagged in §4.5's tone guidance: it compiles, it passes any test that runs single-threaded, and it fails only once two requests genuinely overlap — which local development rarely reproduces.

Scoped state captured by a process-wide singleton
sequenceDiagram participant RA as Request A participant RC as RequestCache.Instance participant RB as Request B RA->>RC: AttachContext(dbA) RB->>RC: AttachContext(dbB) Note over RC: _db now points at dbB RA->>RC: GetCustomer(42) RC-->>RA: queries dbB, NOT dbA

Mistake 3 — mutating the singleton's state without any synchronization

C#
// ❌ Lazy<T> makes CONSTRUCTION thread-safe. It says nothing about the
// mutable Dictionary inside the constructed instance.
public sealed class MetricsRegistry
{
    private static readonly Lazy<MetricsRegistry> _lazy = new(() => new());
    public static MetricsRegistry Instance => _lazy.Value;

    private readonly Dictionary<string, long> _counts = new();
    private MetricsRegistry() { }

    public void Increment(string key) =>
        _counts[key] = _counts.GetValueOrDefault(key) + 1;  // races under load
}

// ✅ The instance is thread-safe to obtain; its state must be made
// thread-safe to mutate, separately and explicitly.
public sealed class MetricsRegistry
{
    private static readonly Lazy<MetricsRegistry> _lazy = new(() => new());
    public static MetricsRegistry Instance => _lazy.Value;

    private readonly ConcurrentDictionary<string, long> _counts = new();
    private MetricsRegistry() { }

    public void Increment(string key) => _counts.AddOrUpdate(key, 1, (_, v) => v + 1);
}
C#
// Step 4 of the refactor: the test-only reset seam, gated behind
// InternalsVisibleTo rather than a public API surface.
[assembly: InternalsVisibleTo("MyApp.Tests")]

public sealed class AppConfig
{
    private static AppConfig? _instance;
    private static readonly Lock _gate = new();

    public static AppConfig Instance
    {
        get
        {
            if (_instance is not null) return _instance;
            using (_gate.EnterScope()) { return _instance ??= Load(); }
        }
    }

    private static AppConfig Load() => new(File.ReadAllText("appsettings.json"));
    private readonly string _raw;
    private AppConfig(string raw) => _raw = raw;

    internal static void ResetForTests()
    {
        using (_gate.EnterScope()) { _instance = null; }
    }
}
15

Refactoring Path — Introducing It Into Existing Code

Starting from §2's AppConfig mess — a class constructed fresh at forty call sites, each re-parsing disk. The path to Singleton, in shippable steps:

  1. Cut the seam first: introduce an internal factory method, AppConfig.Load(), that call sites switch to instead of new AppConfig(). Constructor stays public for now — this step changes nothing behaviourally, it only centralizes the call path. Ship it, verify nothing regressed.
  2. Make Load() cache: back it with a Lazy<AppConfig> internally, still exposed as Load(). Every call site already goes through this method, so this step is invisible externally — one parse instead of forty, same public surface.
  3. Seal the constructor: now that nothing calls new AppConfig() directly (verified by a compiler search, not by memory), make the constructor private and rename Load() to the conventional Instance property. This is the only step that's a genuine breaking change to the public API — and by this point, it breaks nothing, because step 1 already migrated every caller.
  4. Add the test seam: an internal ResetForTests() or a constructor overload visible only via InternalsVisibleTo, so the test suite isn't stuck sharing state across test classes.
Refactoring steps — each one independently shippable
flowchart LR A["Step 1
Introduce Load()
seam, ctor still public"] --> B["Step 2
Load() caches via
Lazy<T> internally"] B --> C["Step 3
Seal constructor,
rename to Instance"] C --> D["Step 4
Add test-only
reset seam"]

What to do about existing call sites: step 1's mechanical find-and-replace (new AppConfig() → AppConfig.Load()) is safe to do in one pass precisely because it changes no behaviour yet — that's what makes the later, actually-breaking step (3) reviewable in isolation, with a diff that's a one-line access-modifier change instead of a forty-file sweep.

ADR fieldContent for this refactor
TitleIntroduce Singleton lifecycle for AppConfig
StatusAccepted
ContextAppConfig is constructed at 40+ call sites, each re-parsing appsettings.json from disk; no consistency guarantee across the process during a config hot-reload
DecisionMigrate to a private constructor + lazily-initialized static Instance, via the four-step seam-first path above
ConsequencesOne parse per process instead of forty; static state must be reset between test runs (mitigated by the added test seam); reintroduces the risk flagged in §11 if this app later needs per-tenant config
16

Reference Checklist

  • Constructor is private — no public, protected, or internal way to construct a second instance
  • Class is sealed, so a subclass can't quietly introduce a second constructible type
  • Construction uses Lazy<T> (or System.Threading.Lock with an explicit double-check) rather than hand-rolled unsynchronized lazy init
  • Access point is a property (Instance), not a GetInstance() method
  • Mutable state inside the instance is separately synchronized — Lazy<T> only protects construction, not later mutation
  • No scoped or per-request dependency (a DbContext, an HttpContext) is ever captured and held by the singleton
  • A test-only reset or injection seam exists — no test suite should be stuck sharing global state with no way to isolate it
  • If a DI container is already present in this app, container singleton lifetime has been considered and consciously rejected, not skipped
  • The "only one, ever" assumption has been stated out loud to the team, not just assumed by the author
17

Sources

Primary

  • Gamma, Helm, Johnson, Vlissides — Design Patterns: Elements of Reusable Object-Oriented Software (1994), the Singleton chapter

Analysis and critique

.NET documentation and API references