C# design patterns that still earn their place

Half the Gang of Four catalogue is now a language feature. The half that survived is worth knowing properly — and worth not reaching for out of habit.

Patterns the language replaced

A pattern is a workaround for something the language cannot say directly. When the language learns to say it, the pattern stops being wisdom and starts being noise. These are the ones I no longer write:

Pattern What replaced it
Singleton AddSingleton<T>(). The container owns the lifetime, and the class stays testable because nothing reaches for a static instance.
Abstract Factory, in most cases Constructor injection, or IEnumerable<T> of every registered implementation.
Builder, for data record with init setters and with expressions.
Visitor Pattern matching on a closed hierarchy. A switch expression over sealed types does the same job in five lines.
Observer, hand-rolled IObservable<T>, events, or a real message broker if it crosses a process.
Singleton is not the same as a singleton lifetime The pattern means a class controls its own instantiation through a static accessor, which makes it global mutable state you cannot substitute in a test. Registering a normal class with a singleton lifetime gives you one instance without any of that. They are frequently confused and they are not the same thing.

Strategy: the one you already use

Strategy is "pick the implementation at runtime", and in a DI container it barely looks like a pattern. The useful version registers every implementation and selects by a key.

public interface IPaymentProvider
{
    string Key { get; }
    Task<Result> ChargeAsync(Payment p, CancellationToken ct);
}

// every provider registered against the same interface
services.AddScoped<IPaymentProvider, CardProvider>();
services.AddScoped<IPaymentProvider, BankTransferProvider>();
services.AddScoped<IPaymentProvider, WalletProvider>();

public class PaymentService(IEnumerable<IPaymentProvider> providers)
{
    public Task<Result> ChargeAsync(Payment p, CancellationToken ct)
    {
        var provider = providers.FirstOrDefault(x => x.Key == p.Method)
            ?? throw new NotSupportedException(p.Method);

        return provider.ChargeAsync(p, ct);
    }
}

Adding a provider is one new class and one registration. No switch statement grows, and nothing existing is edited — which is the whole point.

The tell that you need it A switch on a type or a mode string that gets a new arm every time the business adds an option, in a method that also does other work. If the arms differ only in a value, keep the switch; a dictionary is not a pattern. If they differ in behaviour, make them classes.

Decorator: behaviour without edits

Decorator wraps an implementation in another implementation of the same interface. It is how you add caching, retries, logging or metrics to something without touching it — and how you keep those four concerns from being tangled into the thing that does the actual work.

caller sees IPrices Logging timing, errors Caching hit? return Retry backoff real the work every layer implements the same interface, so any one can be removed
The caller cannot tell how many layers there are. Neither can the innermost class.
public class CachedPrices(IPrices inner, IDistributedCache cache) : IPrices
{
    public async Task<decimal> GetAsync(int sku, CancellationToken ct)
    {
        var key = $"price:{sku}";
        var hit = await cache.GetStringAsync(key, ct);
        if (hit is not null) return decimal.Parse(hit);

        var value = await inner.GetAsync(sku, ct);   // delegate, do not reimplement

        await cache.SetStringAsync(key, value.ToString(), new() {
            AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5)
        }, ct);

        return value;
    }
}

Order matters and is worth thinking about. Caching outside retry means a cache hit never retries, which is what you want. Retry outside caching means you would re-run the cache lookup on every attempt, which is wasted work.

Result: errors that are not exceptions

Exceptions are for the unexpected. "This email is already registered" is not unexpected — it is a normal outcome of a normal operation, and modelling it as an exception means the happy path is decided by a catch block somewhere else.

public readonly record struct Result<T>
{
    public T      Value   { get; init; }
    public string Error   { get; init; }  // a stable code, not a sentence
    public bool   Success => Error is null;
}
Return a code, never a sentence "api.user.email_taken" rather than "That email is already registered". The caller decides the wording, which means the same backend serves two languages without a translation table in the service layer, and a reworded message is not a backend deploy.

The cost is honest: every caller must check. That is the point — the compiler and the reader can both see that this call can fail, which a thrown exception hides.

Mediator: useful and overused

Mediator (MediatR, in practice) turns a method call into a message handled elsewhere. It buys two real things: thin controllers, and a pipeline where validation, logging and transactions apply to every request without being written in every handler.

controller PIPELINE BEHAVIOURS — run for every request validate log transaction handler the actual logic
Cross-cutting concerns live in one place instead of at the top of every handler.

Where it goes wrong is when every call becomes a message. A handler that does nothing but call one service method has added a type, a registration and a layer of indirection in exchange for nothing. Jumping to the definition no longer works; you are grepping for a type name.

My line Use it at the edge — one command or query per endpoint, where the pipeline earns its keep. Do not use it between services inside the same process. In-process messages that nothing else subscribes to are a method call wearing a costume.

Repository: the argument

The case against: Entity Framework's DbContext is already a unit of work and DbSet<T> is already a repository. Wrapping them produces a class whose methods are one-line passthroughs, and the abstraction leaks the moment someone needs Include or projection.

The case for, which I find more convincing in a large codebase: a repository is where you stop query shapes from spreading. Without one, the same five-table join is written slightly differently in eleven places, and when it becomes slow you fix it eleven times.

A real trap, from EF If your interface declares GetAll(bool tracked = false) and the implementation declares tracked = true, a call through the interface silently uses the interface default. You get AsNoTracking, your edit is never persisted, and SaveChanges reports zero rows affected with no error. Default values are resolved at the call site against the static type — put them in one place, or pass the argument explicitly.

How I decide

  • Does the language already do this? If yes, use the language.
  • Is there a second implementation today? One implementation behind an interface is a guess about the future that is usually wrong, and it makes every read one hop longer.
  • Does it make the common change easier? If adding a provider means one new file, the pattern is working. If it means edits in four, it is not.
  • Can a newcomer follow it? A pattern that needs a diagram to navigate is a cost paid by everyone who touches the code afterwards.

The patterns that survive are the ones that answer a question you already had. The ones that go bad are the ones applied before the question was asked.

← All articles