C# / .NET Compendium PLEN
.NET / C# / SOLID, Clean Code, DI

DDD - Domain-Driven Design

What DDD is

Domain-Driven Design (Eric Evans, 2003) is an approach to building complex software in which the model of the business domain is the heart of the application. Instead of starting from tables and controllers, you start by understanding the business and reflect it in code, together with its vocabulary and rules.

DDD is not a framework or a library, but a set of ideas in two layers:

  • Strategic DDD - how to split a large system and how to talk to the business,
  • Tactical DDD - which building blocks (entities, aggregates, ...) to use in the domain code.

DDD makes sense with complex business logic. For simple CRUD it is overkill.

Strategic DDD

Ubiquitous Language

A shared vocabulary of developers and domain experts. The same words are used in conversations, documentation and in code. If the business says "confirm an order", the code has order.Confirm(), not order.SetStatus(2).

Bounded Context

A boundary within which a given model and a given language have one, consistent meaning. The same word means something different in different contexts:

  • "Customer" in the Sales context - has a basket and an order history,
  • "Customer" in the Invoicing context - has a tax ID, a billing address and payment terms.

Instead of one gigantic Customer class there are two models, each in its own context. A Bounded Context is a natural candidate for the boundary of a module (modular monolith) or a microservice.

Context Map and integrating contexts

A map describing how contexts talk to each other (events, APIs). An important pattern: the Anti-Corruption Layer - a translation layer that protects your own model from being "polluted" by someone else's (e.g. an old legacy system).

Subdomains

  • Core domain - what gives a competitive advantage; this is where you invest in the best model and people,
  • Supporting subdomain - needed, but doesn't set the company apart,
  • Generic subdomain - a problem solved the same way everywhere (authentication, payments, e-mail) - buy it or use an off-the-shelf solution.

Tactical DDD - the building blocks of the model

Entity

An object with an identity (Id) that persists even when its data changes. Two orders with the same items are still two different orders. We compare by Id.

Value Object

An object without identity, defined solely by its values; immutable and compared by value. An ideal candidate for a record (see Record - declaration).

public record Money(decimal Amount, string Currency)
{
    public Money Add(Money other)
    {
        if (other.Currency != Currency)
            throw new InvalidOperationException("Different currencies");
        return this with { Amount = Amount + other.Amount };
    }
}

public record Address(string Street, string City, string PostalCode);

Instead of decimal price you use Money price - the compiler makes sure you don't add zlotys to euros, and the rules (e.g. "the amount is not negative") live in one place. This fights the Primitive Obsession anti-pattern.

Aggregate and Aggregate Root

A group of objects treated as one consistent whole when it comes to changes. Access from outside only through the aggregate root, which guards the invariants. Details and an example are in the topic Clean Architecture (the section on aggregates).

public class Order   // Aggregate Root
{
    private readonly List<OrderItem> _items = new();
    public int Id { get; private set; }
    public OrderStatus Status { get; private set; } = OrderStatus.Draft;
    public IReadOnlyList<OrderItem> Items => _items;   // no public Add on the list

    public void AddItem(int productId, int quantity, Money unitPrice)
    {
        if (Status != OrderStatus.Draft)
            throw new DomainException("A confirmed order cannot be changed");
        if (quantity <= 0)
            throw new DomainException("Quantity must be positive");

        _items.Add(new OrderItem(productId, quantity, unitPrice));
    }

    public void Confirm()
    {
        if (!_items.Any())
            throw new DomainException("The order is empty");
        Status = OrderStatus.Confirmed;
    }
}

Aggregate design rules:

  • One transaction = one aggregate (you change one aggregate in one transaction),
  • aggregates are small - they contain only what must be consistent together,
  • you refer to other aggregates by Id, not through an object reference,
  • consistency between aggregates is eventual, e.g. through domain events.

Domain Service

Domain logic that doesn't fit any single entity (e.g. a transfer between two accounts, a price calculation from many sources). It is stateless and operates on domain objects. Not to be confused with an application service.

Domain Event

A fact from the past that matters to the business, named in the past tense: OrderConfirmed, PaymentReceived. It lets you react to changes in other aggregates and contexts without tight coupling.

public record OrderConfirmed(int OrderId, DateTime OccurredAt) : INotification;

Often published by MediatR (INotification) or, for reliability between services, by the Outbox pattern (see Outbox).

Repository

An abstraction of a collection of aggregates - one repository per aggregate (not per table). The interface belongs to the domain layer, the implementation (EF Core) to infrastructure. More: Repository and Unit of Work.

public interface IOrderRepository
{
    Task<Order?> GetAsync(int id, CancellationToken ct);
    void Add(Order order);
}

Factory

When creating an object is complicated or has to enforce invariants, you extract a factory method or class (often just a static method Order.Create(...)).

Anemic model vs rich model

Anemic Domain Model (an anti-pattern in DDD):

public class Order { public List<OrderItem> Items { get; set; } public string Status { get; set; } }
// all the logic is in OrderService - the entity is a bag of data

Rich Domain Model: logic and invariants are in the entity/aggregate (order.AddItem(), order.Confirm()), setters are private, and the state can't get into an invalid condition. Thanks to this you can't "forget" validation in some service.

DDD in .NET - how to put it together

  • Entity Framework Core supports DDD: Fluent API configuration, private setters, private fields (_items), Value Objects as Owned Types (OwnsOne), value conversions.
  • Clean Architecture provides the project structure in which the Domain layer is in the middle and depends on nothing (see Clean Architecture).
  • CQRS + MediatR: the Command Handler loads the aggregate, calls its domain method and saves; the Query Handler reads a DTO straight from the database (see What CQRS is).
public class ConfirmOrderHandler : IRequestHandler<ConfirmOrderCommand>
{
    private readonly IOrderRepository _orders;
    private readonly IUnitOfWork _uow;
    public ConfirmOrderHandler(IOrderRepository orders, IUnitOfWork uow) { _orders = orders; _uow = uow; }

    public async Task Handle(ConfirmOrderCommand cmd, CancellationToken ct)
    {
        var order = await _orders.GetAsync(cmd.OrderId, ct)
                    ?? throw new NotFoundException(cmd.OrderId);

        order.Confirm();                 // logika biznesowa w agregacie
        await _uow.SaveChangesAsync(ct); // handler tylko orkiestruje
    }
}

Layers in DDD

Layer Responsibility
Domain Entities, Value Objects, aggregates, domain events, repository interfaces
Application Use cases (Command/Query Handlers), orchestration, transactions
Infrastructure EF Core, repositories, queues, e-mail, integrations
Presentation API, controllers, UI

When to use DDD and when not to

Use it when: the business logic is complex and changes often, you have access to a domain expert, and the system will be developed for years.

Don't use it when: the application is simple CRUD, the team has no contact with the business, or it is a prototype or a short-lived tool. Costs: more code, a learning curve, the risk of over-engineering.

DDD can be applied selectively - a full model only in the core domain, and plain CRUD in the other parts.

Interview questions

  • Entity vs Value Object? An Entity has an identity (Id) and a lifecycle, a Value Object is immutable and compared by value.
  • What is an aggregate? A transactional consistency boundary with a root that guards the invariants; from outside we modify it only through the root.
  • What is a Bounded Context? A boundary within which the model and language are consistent; the same term can mean something different in different contexts.
  • Why is the anemic model a problem? The logic gets scattered across services, and entities can end up in an invalid state.
  • How do aggregates communicate with each other? Through Ids and domain events, with eventual consistency, not one big transaction.
  • Does DDD require CQRS or Clean Architecture? No - they are independent, although they go well together.
Buy me a coffee