Part 2 of 12 in Clean Architecture in .NET
Setting Up the Domain Layer in Clean Architecture: Rich Entities, Strongly Typed IDs and Result
· 16 min read
The domain layer is where a Clean Architecture project keeps its business rules. This article builds one in .NET, with rich entities, strongly typed IDs, value objects, Result and domain events. It is Part 2 of the Clean Architecture in .NET series.
In Part 1, the solution got its four projects, and Ecommerce.Domain was an empty project that references nothing. This part fills it with the building blocks every feature uses. The examples are EcommerceApp’s products, orders, coupons and users.
Because the domain references nothing, it has no EF Core and no web framework, and it never reads the clock. That makes it the easiest layer to test.
This part explains the building blocks through the most important types. The other entities and value objects follow the same patterns, and they are all in this part’s code.
The base entity
Every entity inherits from one base class, and every aggregate root from a second one on top of it. The first gives an entity its identity:
public abstract class Entity<TId>
{
protected Entity(TId id)
{
Id = id;
}
#pragma warning disable CS8618 // EF Core sets Id after calling this constructor.
protected Entity()
{
}
#pragma warning restore CS8618
public TId Id { get; init; }
}
The second adds domain events:
public abstract class AggregateRoot<TId> : Entity<TId>, IHasDomainEvents
{
private readonly List<IDomainEvent> _pendingEvents = [];
protected AggregateRoot(TId id)
: base(id)
{
}
protected AggregateRoot()
{
}
public IReadOnlyList<IDomainEvent> PullDomainEvents()
{
IDomainEvent[] events = [.. _pendingEvents];
_pendingEvents.Clear();
return events;
}
protected void RecordDomainEvent(IDomainEvent domainEvent)
{
ArgumentNullException.ThrowIfNull(domainEvent);
_pendingEvents.Add(domainEvent);
}
}
IHasDomainEvents and IDomainEvent are two small interfaces next to them:
public interface IHasDomainEvents
{
IReadOnlyList<IDomainEvent> PullDomainEvents();
}
public interface IDomainEvent;
Idhas a type per entity, such asEntity<OrderItemId>orAggregateRoot<ProductId>. Strongly typed IDs are covered below.- Only an aggregate root records domain events. Why? Because the aggregate root is what a handler loads and saves, so it is where something happens. A child such as
OrderItemchanges only through its root, and the root records the event. - The root collects its events in a private list.
RecordDomainEventis protected, so only the root itself can record one. Code outside the domain takes them after saving withPullDomainEvents, which also empties the list, so the same event can’t be handed out twice. IHasDomainEventshas no generic parameter, so code that doesn’t know an aggregate’s ID type can still pull its events.IDomainEventis a marker: it has no members and only says that a record is an event.- The parameterless constructor is for EF Core. When EF Core loads an entity, it can create it through that constructor and set the properties afterwards. Until then, the non-nullable properties have no value, which is what CS8618 warns about. So the warning is turned off only around that constructor, with the reason next to it.
Order,OrderItemandProducthave their own private parameterless constructor with the same#pragma.
Rich entities instead of anemic ones
An anemic entity is only data: public getters and setters, and the rules live in whichever handler uses it. A rich entity keeps the data and the behavior together, so the domain logic is in one place.
In practice that means:
- a private constructor, so an entity can only be created through its own
Createmethod, which enforces the invariants - private setters, so state only changes through the entity’s methods
- read-only collections for child entities
- domain events raised from inside the entity when something needs to react
Here is part of Order, the aggregate root that owns its OrderItems (the constructors, the other properties and the other methods are left out). It uses three types this part covers further down: Money, a value object for an amount and its currency; Result, which holds either success or an error; and OrderErrors, the errors an order can return. OrderId and UserId are strongly typed IDs, also covered below, and OrderStatus is an enum.
public sealed class Order : AggregateRoot<OrderId>
{
private readonly List<OrderItem> _orderItems = [];
public Money TotalPrice { get; private set; }
public Money Discount { get; private set; }
public IReadOnlyList<OrderItem> OrderItems => _orderItems;
public static Order Create(UserId userId, DateTime createdOnUtc)
{
var order = new Order(OrderId.New(), userId, Money.Zero(), OrderStatus.Placed, createdOnUtc);
order.RecordDomainEvent(new OrderPlacedDomainEvent(order.Id));
return order;
}
public Result AddOrderItem(Product product, int quantity, DateTime createdOnUtc)
{
if (quantity <= 0)
{
return Result.Failure(OrderErrors.InvalidQuantity);
}
var lineTotal = new Money(product.Price.Amount * quantity, product.Price.Currency);
if (OrderItems.Count == 0)
{
// The first line sets the order's currency.
TotalPrice = lineTotal;
Discount = Money.Zero(lineTotal.Currency);
}
else
{
Result<Money> total = TotalPrice.Add(lineTotal);
if (total.IsFailure)
{
return Result.Failure(OrderErrors.CurrencyMismatch);
}
TotalPrice = total.Value;
}
_orderItems.Add(OrderItem.Create(Id, product, quantity, createdOnUtc));
return Result.Success();
}
}
There is no other way to add a line, so a handler can’t add one with a zero quantity or mix currencies. Each line also copies the product’s price into UnitPrice, so a later price change doesn’t rewrite a customer’s past order.
Why not a public List<OrderItem>? Because then any caller could call order.OrderItems.Add(...) and skip every check. An IReadOnlyList over a private field closes that, and EF Core still finds the field by its naming convention (_orderItems).
Order.Create can’t fail, but Product.Create can: it returns Result<Product> and rejects a price of zero or less, or negative stock. So a product can’t start in an invalid state either, no matter who creates it.
The entity also never reads the clock. The caller passes createdOnUtc, so a test can pass a fixed date.
Strongly typed IDs
Every entity has its own ID type, created in the domain:
public record ProductId(Guid Value)
{
public static ProductId New() => new(Guid.CreateVersion7());
}
Create calls ProductId.New(), so the entity has its ID before it is saved, and an event raised in Create can carry it. The type stops a CategoryId from being passed where a ProductId is expected.
I use UUIDv7 (Guid.CreateVersion7(), added in .NET 9) instead of Guid.NewGuid(). A v7 ID starts with a millisecond timestamp, so new keys sort roughly in creation order, and PostgreSQL inserts them near the end of the index instead of at random places. Within the same millisecond the rest is random, so the order is only rough.
SQL Server is different: it sorts uniqueidentifier by a different byte order, so v7 keys are effectively random there. On SQL Server, I keep the Guid key nonclustered and add a bigint identity column as the clustered index. The domain never sees that column.
Value objects that can’t be invalid
A value object replaces a primitive with a type that means something: ProductName instead of string, Money instead of a decimal and a currency code next to it. If a caller swaps a ProductName and a ProductDescription, the compiler catches it.
But a type alone isn’t enough: you shouldn’t be able to create a value object in an invalid state. The simplest value object is a one-line record:
public record ProductName(string Value);
That record accepts anything. So each value object gets a private constructor and a Create that returns a Result:
public record ProductName
{
public const int MaxLength = 200;
public static readonly Error Invalid = new("ProductName.Invalid", "The product name is required and can't be longer than 200 characters", HttpStatusCode.BadRequest);
private ProductName(string value)
{
Value = value;
}
public string Value { get; }
public static Result<ProductName> Create(string? value)
{
if (string.IsNullOrWhiteSpace(value) || value.Length > MaxLength)
{
return Result.Failure<ProductName>(Invalid);
}
return new ProductName(value);
}
}
Value has no init, so a with expression can’t skip Create either.
Why validate twice?
An API usually validates incoming commands too, for example with FluentValidation. So why does the value object check as well? FluentValidation and value objects solve different problems. The validator protects one path: the command that comes in through the API. It doesn’t stop another caller from creating an empty name. That caller could be a background job, a data import, another handler, a unit test, or another part of the domain. With the private constructor, new ProductName("") doesn’t compile, and ProductName.Create("") returns a failure.
So the validator stays for early, user-friendly feedback on each field, and the value object guarantees validity on its own.
That doesn’t mean every string needs a wrapper. How I decide:
- If the type gives meaningful type safety, I keep it, even when FluentValidation does the same checks.
- If the type owns business rules or behavior, I keep it and enforce those rules inside it.
- If it is only a wrapper and the distinction has no practical benefit, a primitive may be enough.
- If the wrapper is supposed to guarantee validity but allows invalid values, I fix how it is constructed.
Money is a value object with behavior. Adding two amounts could be a + operator that throws when the currencies differ. Instead, Money.Add returns a Result with Money.CurrencyMismatch, for the reason in the next section:
public record Money(decimal Amount, Currency Currency)
{
public static readonly Error CurrencyMismatch = new("Money.CurrencyMismatch", "Amounts in different currencies can't be added", HttpStatusCode.BadRequest);
public Result<Money> Add(Money other)
{
if (Currency != other.Currency)
{
return Result.Failure<Money>(CurrencyMismatch);
}
return new Money(Amount + other.Amount, Currency);
}
public static Money Zero() => new(0, Currency.None);
public static Money Zero(Currency currency) => new(0, currency);
}
Subtract has the same shape as Add. Currency is a value object too, created from an ISO code with Currency.FromCode. Money.Zero() uses Currency.None, which is why Order.AddOrderItem above sets the first line’s total instead of adding it to zero, and starts the discount at zero in the line’s currency.
Result for expected failures, exceptions for the rest
Both success and failure are part of the business flow. When a product isn’t found by its ID, we already know what to do: return a “not found” result with a message that means something to the user. That isn’t exceptional, so it shouldn’t be an exception.
A Result holds either success or an error, and Result<TValue> also carries the value:
public class Result
{
private protected Result(Error error)
{
Error = error;
}
public Error Error { get; }
public bool IsSuccess => Error == Error.None;
public bool IsFailure => !IsSuccess;
public static Result Success() => new(Error.None);
public static Result Failure(Error error) => new(RequireFailure(error));
public static Result<TValue> Success<TValue>(TValue value) => new(value);
public static Result<TValue> Failure<TValue>(Error error) => new(RequireFailure(error));
private protected static Error RequireFailure(Error error)
{
ArgumentNullException.ThrowIfNull(error);
return error == Error.None
? throw new ArgumentException("A failed result needs an error other than Error.None.", nameof(error))
: error;
}
}
public sealed class Result<TValue> : Result
{
private readonly TValue? _value;
internal Result(TValue value)
: base(Error.None)
{
_value = value;
}
internal Result(Error error)
: base(error)
{
}
// Reading the value of a failure is a bug in the caller, not a business outcome.
public TValue Value => IsSuccess
? _value!
: throw new InvalidOperationException($"A failed result has no value. Error: {Error.Name}.");
// A handler can return its response directly; a null response becomes Error.NullValue.
public static implicit operator Result<TValue>(TValue? value) =>
value is null ? new Result<TValue>(Error.NullValue) : new Result<TValue>(value);
}
A result is a success exactly when its error is Error.None. So there is no separate success flag that could disagree with the error, and Failure refuses Error.None, because a failure without an error tells the caller nothing.
Where I draw the line:
- Expected business rejection →
Result. The request is legitimate, but a business rule may reject it: the product doesn’t have enough stock, an order mixes currencies, a rating is outside 1–5. - Unexpected or exceptional failure → exception. The application can’t safely continue, or there is a bug: the database connection fails, an unexpected null or invalid internal state, an infrastructure dependency is unavailable, an unexpected I/O error.
So Money.Add returns a Result, and so does Currency.FromCode for an unknown currency code. A few throws stay on purpose. Reading .Value of a failed Result throws, because that is a bug in the caller. And if the database returns a product name that ProductName.Create rejects, .Value throws there too, because the data is corrupt.
An error is a record with a name, a description and a status code. Error.None is the “no error” that a successful Result carries. Error.NullValue is what a Result<TValue> becomes when a handler returns a null value:
public record Error(string Name, string Description, HttpStatusCode Code)
{
public static readonly Error None =
new(string.Empty, string.Empty, HttpStatusCode.InternalServerError);
public static readonly Error NullValue =
new("Error.NullValue", "Null value was provided", HttpStatusCode.BadRequest);
public static Error BadRequest(string name, string description) =>
new(name, description, HttpStatusCode.BadRequest);
// NotFound, Conflict, Unauthorized and InternalServerError have the same shape.
}
Each entity has a static class with its errors, so every failure has one name and one message:
public static class ProductErrors
{
public static readonly Error InsufficientStock = new(
"Product.InsufficientStock",
"The product doesn't have enough stock for the requested quantity",
HttpStatusCode.Conflict);
}
Insufficient stock is a 409 Conflict, not a 400: the request is valid, but it conflicts with the product’s current stock, and the same request can succeed after a restock.
The error carries its HTTP status code, so the API turns any failure into a response with one mapping method. HttpStatusCode comes from System.Net, so the domain still has no package references. The cost is that the domain knows HTTP’s vocabulary, and a caller that isn’t HTTP, such as an event handler or a message consumer, gets a status code it has no use for. The alternative is an error type enum in the domain, mapped to status codes in the API. I preferred HttpStatusCode. Why? Because the status codes I need are already built into that enum, and it ends up as the HTTP status code in the API response anyway.
Domain events
Placing an order should send a confirmation email, but Order shouldn’t know that email exists. So Order.Create raises OrderPlacedDomainEvent, and whatever needs to react handles it:
public sealed record OrderPlacedDomainEvent(OrderId OrderId) : IDomainEvent;
The event carries only the ID, and whatever handles it loads what it needs. The aggregate root collects its events, and they are dispatched only after the order is saved. So an order that is rejected for stock and never saved sends nothing.
The cost: if a handler fails, the order is already saved, but the request still fails. A client that retries places a second order.
In EcommerceApp, UserCreatedDomainEvent sends a welcome email and OrderPlacedDomainEvent sends an order confirmation. The code that reacts lives outside the domain, so the domain doesn’t know about email.
A domain service for a rule across aggregates
Most rules belong to one entity. I reach for a domain service when the rule:
- works on more than one aggregate
- needs stored data from outside them, such as a pricing rule
- is a business operation that no single aggregate owns
Placing an order with a coupon meets all three. The order gets its lines, each product loses stock, and the coupon counts one more use. The discount comes from the coupon’s rule: a percentage, a validity period and a usage limit, stored in the database. And no single one of Order, Product or Coupon should own “place an order”. If Order redeemed the coupon and removed the stock itself, it would be changing two other aggregates.
So the rule lives in a domain service, OrderPlacementService, next to Order. Its Place method:
public static Result<Order> Place(UserId userId, IReadOnlyList<(Product Product, int Quantity)> lines, Coupon? coupon, DateTime utcNow)
{
if (lines.Count == 0)
{
return Result.Failure<Order>(OrderErrors.Empty);
}
var order = Order.Create(userId, utcNow);
foreach ((Product product, int quantity) in lines)
{
Result addItemResult = order.AddOrderItem(product, quantity, utcNow);
if (addItemResult.IsFailure)
{
return Result.Failure<Order>(addItemResult.Error);
}
Result removeStockResult = product.RemoveStock(quantity, utcNow);
if (removeStockResult.IsFailure)
{
return Result.Failure<Order>(removeStockResult.Error);
}
}
if (coupon is not null)
{
Result redeemResult = coupon.Redeem(utcNow);
if (redeemResult.IsFailure)
{
return Result.Failure<Order>(redeemResult.Error);
}
order.ApplyDiscount(coupon.Id, coupon.CalculateDiscount(order.TotalPrice));
}
return order;
}
Each aggregate still enforces its own rules: AddOrderItem checks quantity and currency, RemoveStock checks the stock, and Redeem checks the period and the usage limit. The service only decides the order of the calls. Stock is checked before the coupon, so an order rejected for stock doesn’t use up a coupon.
Why not put this in the PlaceOrder handler?
- The handler’s job is to load, call the domain and save. The rule is business logic, so it belongs with the rest of the business logic.
- In the domain it is tested with plain unit tests, with no database and no mocks.
- Every caller gets the same rule. Cancelling works the same way:
OrderCancellationServicegives back the stock and the coupon use, andOrder.Cancelisinternal, so a handler can’t cancel an order and forget the stock.
ApplyDiscount is internal for the same reason: only the service can apply a discount, in the same step that redeems the coupon.
There is one failure case to watch. If a later line fails, the earlier products have already lost stock in memory. That’s safe as long as nothing saves after a failure.
Both services are static classes because they have no dependencies. As instance methods, they would be flagged by the analyzers from Part 1 (CA1822 and S2325). A service that needs an interface declared in the domain becomes a normal class.
Testing the domain
Because the domain has no dependencies, its tests need no database and no mocks. They go in a test project, Ecommerce.Domain.UnitTests, that references only the Domain project:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit.v3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Ecommerce.Domain\Ecommerce.Domain.csproj" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
</Project>
Microsoft.NET.Test.Sdk and xunit.v3 already have a PackageVersion from Part 1. coverlet.collector collects code coverage, and it needs one more line under the Tests label in Directory.Packages.props:
<PackageVersion Include="coverlet.collector" Version="10.1.0" />
Add the project to EcommerceApp.slnx with dotnet sln add Ecommerce.Domain.UnitTests. Its test names use underscores too, so add it to the CA1707 section from Part 1:
[{Ecommerce.ArchitectureTests,Ecommerce.Domain.UnitTests}/**.cs]
And add this line to the CI test step from Part 1:
dotnet test --project Ecommerce.Domain.UnitTests --no-build --configuration Release
The tests create entities with their factories and call the methods:
[Fact]
public void Place_Should_NotRedeemTheCoupon_WhenStockIsInsufficient()
{
Product keyboard = CreateProduct(100m, Currency.Usd, quantity: 1);
Coupon coupon = CreateCoupon(percentOff: 10, maxRedemptions: 5);
Result<Order> result = OrderPlacementService.Place(UserId.New(), [(keyboard, 2)], coupon, UtcNow);
Assert.Equal(ProductErrors.InsufficientStock, result.Error);
Assert.Equal(0, coupon.RedemptionCount);
}
UtcNow is a fixed date in the test class, and CreateProduct and CreateCoupon are small helpers there. They call Product.Create and Coupon.Create with valid values and take .Value, so each test only sets what it is about:
internal static Product CreateProduct(decimal priceAmount, Currency currency, int quantity)
{
return Product.Create(
ProductName.Create("Keyboard").Value,
ProductDescription.Create("Mechanical keyboard").Value,
new Money(priceAmount, currency),
quantity,
CategoryId.New(),
UtcNow).Value;
}
The tests assert against the error instances from {Entity}Errors, not against messages, so rewording a message doesn’t break them.
Ecommerce.Domain.UnitTests has 75 tests, covering the value objects, Money, Currency, the category, order, stock and coupon rules, both domain services and the events. They run with dotnet test --project Ecommerce.Domain.UnitTests/Ecommerce.Domain.UnitTests.csproj. That’s the working state for this part: the domain compiles with no references, and its rules are tested on their own.
The full code at the end of this part is at series-part-2.