Volume 6 · Chapter 4 — Enterprise Application Architecture and Design Patterns

Enterprise Design Patterns

Goutham Mayaluri 7 min read .NETC#

4.1 Introduction

Design patterns are named, reusable solutions to recurring design problems. In enterprise .NET, a handful of them appear again and again because they map cleanly onto the concerns of long-lived systems: isolating persistence, coordinating transactions, varying behaviour at runtime, and adding cross-cutting concerns without editing existing code. This chapter treats each pattern not as trivia but as a tool with a specific force it resolves and a cost it imposes.

4.2 Repository Pattern

The Repository pattern gives the domain a collection-like abstraction over persistence, so business code depends onIOrderRepositoryrather than onDbContext. Its real value is decoupling and testability - but note that EF Core’sDbSetis already a repository andDbContextis already a unit of work, so a repository that merely forwards calls adds nothing. Add one when you want to centralise query logic, hide the ORM, or express domain-specific retrieval.


public interface IOrderRepository
{
    Task<Order?> GetByIdAsync(OrderId id, CancellationToken ct);
    Task<IReadOnlyList<Order>> GetOverdueAsync(CancellationToken ct); // domain query
    void Add(Order order);
}

4.3 Unit of Work Pattern

Unit of Work tracks a set of changes and commits them as one atomic transaction. It ensures that multiple repository operations either all succeed or all roll back. In EF Core,SaveChangesAsyncis the unit of work; wrapping it behindIUnitOfWorkkeeps the application layer free of EF types.

4.4 Factory Pattern

Factories encapsulate creation logic so clients do not need to know which concrete type to build or how to assemble it. In enterprise code this often means selecting an implementation by runtime data - a payment provider by country, a report generator by format.


public interface IPaymentGatewayFactory
{
    IPaymentGateway Create(string country);
}

public sealed class PaymentGatewayFactory : IPaymentGatewayFactory
{
    private readonly IServiceProvider _sp;
    public IPaymentGateway Create(string country) => country switch
    {
        "US" => _sp.GetRequiredService<StripeGateway>(),
        "IN" => _sp.GetRequiredService<RazorpayGateway>(),
        _    => _sp.GetRequiredService<DefaultGateway>()
    };
}

4.5 Strategy Pattern

Strategy lets you select an algorithm at runtime by programming to an interface. It replaces sprawlingswitchstatements with polymorphism and is a direct expression of the Open/Closed Principle: new strategies are added, not edited in.

flowchart TB
  Ctx["PaymentService"] --> I["IPaymentStrategy"]
  I --> A["CreditCardStrategy"]
  I --> B["BankTransferStrategy"]
  I --> C["WalletStrategy"]

4.6 Specification Pattern

The Specification pattern encapsulates a business rule or query predicate as a first-class, composable object. Specifications can be combined with And/Or/Not and reused across validation and querying, keeping rules out of scatteredifstatements.


public sealed class EligibleForLoanSpec : Specification<Customer>
{
    public override Expression<Func<Customer, bool>> ToExpression() =>
        c => c.CreditScore >= 650 && c.IsKycVerified && c.Age >= 18;
}

// Reused in-memory for validation and translated to SQL for querying.
bool ok = new EligibleForLoanSpec().IsSatisfiedBy(customer);

4.7 Mediator Pattern

The Mediator pattern routes requests through a central dispatcher so senders and handlers do not reference each other directly. In .NET this underpins CQRS: a controller sends a command object and MediatR resolves the matching handler, with pipeline behaviours layering in validation and logging.

4.8 Decorator Pattern

Decorator wraps an object to add behaviour without changing it, satisfying Open/Closed. It is the natural way to add caching, logging, retries, or authorization around a service - each concern is a thin wrapper composed at registration time.


public sealed class CachingProductQuery : IProductQuery
{
    private readonly IProductQuery _inner;
    private readonly IMemoryCache _cache;

    public Task<Product?> GetAsync(ProductId id) =>
        _cache.GetOrCreateAsync(id, _ => _inner.GetAsync(id));
}
// Registration composes the chain: Caching -> Logging -> real query.

4.9 Observer Pattern

Observer lets objects publish state changes to interested subscribers without knowing who they are. In enterprise .NET this shows up as domain events,IObservable<T>streams, and event-driven notification flows.

4.10 Adapter and Template Method

Adaptermakes an incompatible interface usable by wrapping it - essential when integrating legacy or third-party systems.Template Methoddefines the skeleton of an algorithm in a base class while letting subclasses fill in specific steps, useful for standardised workflows like an ETL pipeline where only the transform differs.

Senior Interview Question

When should design patterns not be used?

When there is no recurring problem to solve. Applying a pattern speculatively - a repository over a single query, a factory for an object with one constructor, a strategy interface with one implementation - adds indirection and cognitive load without buying flexibility. Patterns are a response to real forces (anticipated variation, a cross-cutting concern, a coupling you must break). If that force is absent, the simplest code that works is the better design.

Senior Interview Question

Do you still need the Repository pattern with EF Core?

Not automatically.DbSet<T>already behaves like a repository andDbContextis a unit of work, so a pass-through repository is redundant and even hides useful EF features like change tracking and eager loading. A repository earns its place when you want to keep EF types out of the domain, centralise complex or reused query logic behind domain-meaningful methods, or make the write model swappable and easily unit-testable. Otherwise, using EF directly in the application layer is a legitimate, simpler choice.

Senior Interview Question

What is the difference between the Strategy and the State patterns?

Both delegate behaviour to an interchangeable object, but the intent differs. Strategy selects an algorithm chosen by the caller or configuration - which payment method to use - and the strategies are typically independent and stateless. State models an object whose behaviour changes as its internal state transitions, and the state objects usually control the transitions between themselves (an order moving Draft -> Submitted -> Shipped). Strategy varies “how,” State varies “what happens next based on where we are.”

Senior Interview Question

How does the Decorator pattern differ from inheritance for adding behaviour?

Inheritance fixes the added behaviour at compile time and can lead to a combinatorial explosion of subclasses (CachedLoggedRetryingService). Decorator composes behaviour at runtime by wrapping - you can stack caching, logging, and retry in any order and choose the combination at registration. It keeps each concern in its own single-responsibility class and honours Open/Closed. The trade-off is more objects and a longer call chain, which can make stack traces harder to read.

Principal Engineer Question

How do you choose the right design pattern for a problem?

I start from the force, not the catalogue: what is likely to change, what coupling is hurting us, what concern is cross-cutting? Then I pick the simplest construct that resolves that force and no more. I weigh the cost - indirection, more types, harder debugging - against the optionality gained, and I prefer to refactortoa pattern when the need becomes concrete rather than predict it upfront. I also consider the team: a pattern the team does not understand becomes a liability. The best pattern is often “none yet.”

Principal Engineer Question

How would you implement cross-cutting concerns (logging, validation, retry) cleanly across an enterprise app?

I’d avoid scattering them through business code and instead centralise them at well-defined seams. For request handling, MediatR pipeline behaviours (or middleware) apply validation, logging, and transactions uniformly around every command. For service calls, decorators or a library like Polly add retry, timeout, and circuit-breaking declaratively. For broad concerns, ASP.NET Core middleware and interceptors work at the framework boundary. The principle is that a cross-cutting concern should be defined once and composed in, so adding a new handler automatically inherits the behaviour and no engineer can forget it.

4.11 Banking Enterprise Scenario

A banking platform layers these patterns deliberately: Repository and Unit of Work isolate the ledger from EF Core; a Factory selects the correct payment gateway per region; Strategy encapsulates each settlement algorithm; Mediator routes commands and queries with validation and logging behaviours; Decorators add caching and audit around read services; and Observer-style domain events notify fraud and notification modules when a transfer completes. Each pattern is present because a concrete force demanded it, not for its own sake.

Chapter Revision Notes

  • Patterns resolve specific forces - use them only when the force exists.
  • Repository/Unit of Work isolate persistence; skip them if EF suffices.
  • Strategy and Factory vary behaviour and creation at runtime (Open/Closed).
  • Decorator and Mediator pipelines add cross-cutting concerns without edits.
  • Prefer refactoring to a pattern over speculative abstraction.