Domain models and invariants
Domain models and invariants
A domain model represents business concepts and protects rules that must always hold. An aggregate is a consistency boundary controlled through its root, not merely a collection of related database tables.
Use a ubiquitous language: the same words should mean the same thing within a bounded context. Ordering may call an item a purchased line, while fulfillment calls it a shipment unit; each model serves a different purpose. An entity has identity over time; a value object is defined by its meaningful values, preferably immutable. An aggregate root controls changes to related objects so invariants (conditions that must remain true) cannot be bypassed through public setters or exposed mutable lists. Inventory must never fall below zero and reservation quantity must be positive. An aggregate is not automatically a database transaction, but persistence must enforce its consistency boundary even under concurrency; use a conditional update or optimistic concurrency token and handle conflicts. Avoid making all entities one large aggregate. Domain events record facts that occurred; external integration events are separately mapped and published only after the durable transaction succeeds. A handler can fail, so durable publication requires an outbox or equivalent mechanism. A value object that validates a constructor must consider default values if implemented as a struct. These examples use synthetic data and single-threaded state; the event collection in the final example is a model only.
Baseline: .NET 10 / C# 14. All C# results below are reasoned, not executed. Offline models and multi-project labs are explicitly distinguished.
Protect a stock invariant at the root
Reserve two units, then try too much and a negative amount. Rejection must leave stock unchanged.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;var stock = new Inventory(5);foreach (int quantity in new[] { 2, 4, -1 }) { bool accepted = stock.TryReserve(quantity); Console.WriteLine($"{accepted}: {stock.Available}");}sealed class Inventory { public int Available { get; private set; } public Inventory(int initial) { if (initial < 0) throw new ArgumentOutOfRangeException(nameof(initial)); Available = initial; } public bool TryReserve(int quantity) { if (quantity <= 0 || quantity > Available) return false; Available -= quantity; return true; }}Expected result (not executed):
True: 3False: 3False: 3The root is the only writer. Validation precedes mutation, so an unsuccessful reservation leaves the prior state unchanged. This object alone does not prevent lost updates between processes.
Represent a value object with validated equality
Use a sealed record with a get-only property. Two quantities with equal values compare equal; invalid values are rejected.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;var first = new Quantity(2);var second = new Quantity(2);Console.WriteLine(first == second);try { _ = new Quantity(0); }catch (ArgumentOutOfRangeException) { Console.WriteLine("invalid quantity"); }sealed record Quantity { public int Units { get; } public Quantity(int units) { if (units <= 0) throw new ArgumentOutOfRangeException(nameof(units)); Units = units; }}Expected result (not executed):
Trueinvalid quantityA record provides value equality for its stored data. A get-only property prevents normal object initializers or with expressions from assigning an invalid Units value. Entity equality has different identity semantics.
Capture a domain fact only after a successful change
Collect a domain event in a local model. A failed operation emits no event; persistence and dispatch are deliberately absent.
Use the archived Fixture.csproj with an approved .NET 10 SDK. No third-party packages are required. Inspect the project, then build and run with the approved SDK.
using System;using System.Collections.Generic;var order = new Order("order-1");Console.WriteLine(order.TryConfirm());Console.WriteLine(order.TryConfirm());foreach (var fact in order.Events) Console.WriteLine(fact.OrderId);sealed record OrderConfirmed(string OrderId);sealed class Order(string id) { private bool confirmed; private readonly List<OrderConfirmed> events = []; public IReadOnlyList<OrderConfirmed> Events => events.AsReadOnly(); public bool TryConfirm() { if (confirmed) return false; confirmed = true; events.Add(new OrderConfirmed(id)); return true; }}Expected result (not executed):
TrueFalseorder-1The read-only wrapper prevents clients from mutating the list through the exposed API; it is a live view, not an immutable snapshot. The application must persist the change and durable publication intent before announcing success to other systems.
Apply the concept
Extend Inventory with a reservation ID and cancellation operation. Define what duplicate reservation and cancellation requests do, then test invalid quantities and repeated cancellation.
Use the manual practice and knowledge check. Do not deploy or publish these fixtures.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Domain models and invariants — knowledge check
Apply the lesson concepts to the following scenarios.
Which type typically has identity over time?
What defines an aggregate boundary?
What should a rejected reservation do to available stock?
Two processes load the same stock simultaneously. What is additionally needed?
When may an external integration event announce a committed change?