Skip to main content

Lesson 2 of 8

Domain-Driven Design - Aggregates & Value Objects

DDD models complex business domains with: Entities (have identity, can mutate), Value Objects (no identity, equality by value, immutable), Aggregates (cluster of entities with a root that enforces invariants), and Domain Events (record what happened). The domain layer contains all business rules - no EF Core, no HTTP, no infrastructure.

30 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Order Aggregate with Domain Events

Order Aggregate with Domain Events
// ━━ Value Objects - immutable, equality by value ━━
public sealed class Money : IEquatable<Money>
{
    public decimal Amount { get; }
    public string Currency { get; }

    private Money(decimal amount, string currency)
    {
        if (amount < 0) throw new DomainException("Amount cannot be negative");
        if (string.IsNullOrWhiteSpace(currency) || currency.Length != 3)
            throw new DomainException("Currency must be a 3-letter ISO code");

        Amount = Math.Round(amount, 2);
        Currency = currency.ToUpper();
    }

    public static Money Of(decimal amount, string currency) => new(amount, currency);
    public static Money Zero(string currency) => new(0, currency);

    public Money Add(Money other)
    {
        if (Currency != other.Currency)
            throw new DomainException($"Cannot add {Currency} and {other.Currency}");
        return new Money(Amount + other.Amount, Currency);
    }

    public Money Multiply(int quantity) => new(Amount * quantity, Currency);

    // Equality by value (struct-like behavior in class)
    public bool Equals(Money? other) => other is not null && Amount == other.Amount && Currency == other.Currency;
    public override bool Equals(object? obj) => Equals(obj as Money);
    public override int GetHashCode() => HashCode.Combine(Amount, Currency);
    public override string ToString() => $"{Amount:0.00} {Currency}";
}

// ━━ Domain events - record what happened ━━
public abstract class DomainEvent
{
    public Guid Id { get; } = Guid.NewGuid();
    public DateTime OccurredAt { get; } = DateTime.UtcNow;
}

public sealed class OrderPlacedEvent(Guid orderId, Guid customerId, Money total) : DomainEvent
{
    public Guid OrderId { get; } = orderId;
    public Guid CustomerId { get; } = customerId;
    public Money Total { get; } = total;
}

// ━━ Aggregate Root - enforces invariants, owns events ━━
public class Order : Entity<Guid>, IAggregateRoot
{
    private readonly List<OrderItem> _items = [];
    private readonly List<DomainEvent> _events = [];

    public Guid CustomerId { get; private set; }
    public OrderStatus Status { get; private set; } = OrderStatus.Draft;
    public Money Total { get; private set; } = Money.Zero("USD");
    public IReadOnlyList<OrderItem> Items => _items.AsReadOnly();
    public IReadOnlyList<DomainEvent> Events => _events.AsReadOnly();

    // Private constructor - use factory methods
    private Order() { }

    // ━━ Factory method - validates, creates, and raises event ━━
    public static Order Create(Guid customerId)
    {
        var order = new Order { Id = Guid.NewGuid(), CustomerId = customerId };
        return order;
    }

    // ━━ Domain behavior - not just setters ━━
    public void AddItem(Guid productId, Money unitPrice, int quantity)
    {
        if (Status != OrderStatus.Draft)
            throw new DomainException($"Cannot add items to {Status} order");

        if (quantity <= 0)
            throw new DomainException("Quantity must be positive");

        var existing = _items.FirstOrDefault(i => i.ProductId == productId);
        if (existing is not null)
            existing.IncreaseQuantity(quantity);
        else
            _items.Add(new OrderItem(Guid.NewGuid(), productId, unitPrice, quantity));

        RecalculateTotal();
    }

    public void Place()
    {
        if (_items.Count == 0)
            throw new DomainException("Order must have at least one item");
        if (Status != OrderStatus.Draft)
            throw new DomainException("Only draft orders can be placed");

        Status = OrderStatus.Placed;

        // Raise domain event - handlers send email, deduct inventory, etc.
        _events.Add(new OrderPlacedEvent(Id, CustomerId, Total));
    }

    public void ClearEvents() => _events.Clear();

    private void RecalculateTotal() =>
        Total = _items.Aggregate(Money.Zero("USD"),
            (sum, item) => sum.Add(item.UnitPrice.Multiply(item.Quantity)));
}

public class OrderItem(Guid id, Guid productId, Money unitPrice, int quantity)
{
    public Guid Id { get; } = id;
    public Guid ProductId { get; } = productId;
    public Money UnitPrice { get; } = unitPrice;
    public int Quantity { get; private set; } = quantity;
    public void IncreaseQuantity(int by) { Quantity += by; }
}

public enum OrderStatus { Draft, Placed, Processing, Shipped, Delivered, Cancelled }

// Placeholder base types
public abstract class Entity<TId> { public TId Id { get; set; } = default!; }
public interface IAggregateRoot { }
class DomainException : Exception { public DomainException(string m) : base(m) { } }

Tip

Tip

Practice DomainDriven Design Aggregates Value Objects in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagram…

.NET provides a unified platform for building various application types

Practice Task

Note

Practice Task - (1) Write a working example of DomainDriven Design Aggregates Value Objects from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with DomainDriven Design Aggregates Value Objects is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.

Topics in This Module

0/8 done