dotnet-domain-modeling
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesedotnet-domain-modeling
dotnet-domain-modeling
Domain-Driven Design tactical patterns in C#. Covers aggregate roots, entities, value objects, domain events, integration events, domain services, repository contract design, and the distinction between rich and anemic domain models. These patterns apply to the domain layer itself -- the pure C# model that encapsulates business rules -- independent of any persistence technology.
Out of scope: EF Core configuration and aggregate persistence mapping -- see [skill:dotnet-efcore-architecture]. Tactical EF Core usage (DbContext lifecycle, migrations, interceptors) -- see [skill:dotnet-efcore-patterns]. Input validation at API boundaries -- see [skill:dotnet-validation-patterns]. Choosing between EF Core, Dapper, and ADO.NET -- see [skill:dotnet-data-access-strategy]. Vertical slice architecture and request pipeline patterns -- see [skill:dotnet-architecture-patterns]. Messaging infrastructure and saga orchestration -- see [skill:dotnet-messaging-patterns].
Cross-references: [skill:dotnet-efcore-architecture] for aggregate persistence and repository implementation with EF Core, [skill:dotnet-efcore-patterns] for DbContext configuration and migrations, [skill:dotnet-architecture-patterns] for vertical slices and request pipeline design, [skill:dotnet-validation-patterns] for input validation patterns, [skill:dotnet-messaging-patterns] for integration event infrastructure.
C# 中的领域驱动设计战术模式,涵盖聚合根、实体、值对象、领域事件、集成事件、领域服务、仓储契约设计,以及富领域模型和贫血领域模型的区别。这些模式适用于领域层本身——即封装业务规则的纯C#模型——与任何持久化技术无关。
超出范围内容: EF Core配置和聚合持久化映射——参见 [skill:dotnet-efcore-architecture]。EF Core战术使用(DbContext生命周期、迁移、拦截器)——参见 [skill:dotnet-efcore-patterns]。API边界的输入校验——参见 [skill:dotnet-validation-patterns]。EF Core、Dapper和ADO.NET的选型——参见 [skill:dotnet-data-access-strategy]。垂直切片架构和请求管道模式——参见 [skill:dotnet-architecture-patterns]。消息基础设施和saga编排——参见 [skill:dotnet-messaging-patterns]。
交叉引用:聚合持久化和基于EF Core的仓储实现参见 [skill:dotnet-efcore-architecture],DbContext配置和迁移参见 [skill:dotnet-efcore-patterns],垂直切片和请求管道设计参见 [skill:dotnet-architecture-patterns],输入校验模式参见 [skill:dotnet-validation-patterns],集成事件基础设施参见 [skill:dotnet-messaging-patterns]。
Aggregate Roots and Entities
聚合根与实体
An aggregate is a cluster of domain objects treated as a single unit for data changes. The aggregate root is the entry point -- all modifications to the aggregate pass through it.
聚合是一组领域对象的集群,在数据变更时被视为单个单元。聚合根是入口点——对聚合的所有修改都要通过它完成。
Entity Base Class
实体基类
Entities have identity that persists across state changes. Use a base class to standardize identity and equality:
csharp
public abstract class Entity<TId> : IEquatable<Entity<TId>>
where TId : notnull
{
// default! required for ORM hydration; Id is set immediately after construction
public TId Id { get; protected set; } = default!;
protected Entity() { } // Required for ORM hydration
protected Entity(TId id) => Id = id;
public override bool Equals(object? obj) =>
obj is Entity<TId> other && Equals(other);
public bool Equals(Entity<TId>? other) =>
other is not null
&& GetType() == other.GetType()
&& EqualityComparer<TId>.Default.Equals(Id, other.Id);
public override int GetHashCode() =>
EqualityComparer<TId>.Default.GetHashCode(Id);
public static bool operator ==(Entity<TId>? left, Entity<TId>? right) =>
Equals(left, right);
public static bool operator !=(Entity<TId>? left, Entity<TId>? right) =>
!Equals(left, right);
}实体具有跨状态变化保持不变的唯一标识,使用基类来标准化标识和相等性判断:
csharp
public abstract class Entity<TId> : IEquatable<Entity<TId>>
where TId : notnull
{
// default! 是ORM实例化所需;Id会在构造后立即赋值
public TId Id { get; protected set; } = default!;
protected Entity() { } // ORM实例化所需
protected Entity(TId id) => Id = id;
public override bool Equals(object? obj) =>
obj is Entity<TId> other && Equals(other);
public bool Equals(Entity<TId>? other) =>
other is not null
&& GetType() == other.GetType()
&& EqualityComparer<TId>.Default.Equals(Id, other.Id);
public override int GetHashCode() =>
EqualityComparer<TId>.Default.GetHashCode(Id);
public static bool operator ==(Entity<TId>? left, Entity<TId>? right) =>
Equals(left, right);
public static bool operator !=(Entity<TId>? left, Entity<TId>? right) =>
!Equals(left, right);
}Aggregate Root Base Class
聚合根基类
The aggregate root extends and collects domain events:
Entitycsharp
public abstract class AggregateRoot<TId> : Entity<TId>
where TId : notnull
{
private readonly List<IDomainEvent> _domainEvents = [];
public IReadOnlyList<IDomainEvent> DomainEvents =>
_domainEvents.AsReadOnly();
protected AggregateRoot() { }
protected AggregateRoot(TId id) : base(id) { }
protected void RaiseDomainEvent(IDomainEvent domainEvent) =>
_domainEvents.Add(domainEvent);
public void ClearDomainEvents() => _domainEvents.Clear();
}聚合根继承自并收集领域事件:
Entitycsharp
public abstract class AggregateRoot<TId> : Entity<TId>
where TId : notnull
{
private readonly List<IDomainEvent> _domainEvents = [];
public IReadOnlyList<IDomainEvent> DomainEvents =>
_domainEvents.AsReadOnly();
protected AggregateRoot() { }
protected AggregateRoot(TId id) : base(id) { }
protected void RaiseDomainEvent(IDomainEvent domainEvent) =>
_domainEvents.Add(domainEvent);
public void ClearDomainEvents() => _domainEvents.Clear();
}Concrete Aggregate Example
具体聚合示例
csharp
public sealed class Order : AggregateRoot<Guid>
{
public CustomerId CustomerId { get; private set; } = default!;
public OrderStatus Status { get; private set; }
public Money Total { get; private set; } = Money.Zero("USD");
private readonly List<OrderLine> _lines = [];
public IReadOnlyList<OrderLine> Lines => _lines.AsReadOnly();
private Order() { } // ORM constructor
public static Order Create(CustomerId customerId)
{
var order = new Order(Guid.NewGuid())
{
CustomerId = customerId,
Status = OrderStatus.Draft
};
order.RaiseDomainEvent(new OrderCreated(order.Id, customerId));
return order;
}
public void AddLine(ProductId productId, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
throw new DomainException("Cannot modify a non-draft order.");
if (quantity <= 0)
throw new DomainException("Quantity must be positive.");
var line = new OrderLine(productId, quantity, unitPrice);
_lines.Add(line);
RecalculateTotal();
}
public void Submit()
{
if (Status != OrderStatus.Draft)
throw new DomainException("Only draft orders can be submitted.");
if (_lines.Count == 0)
throw new DomainException("Cannot submit an empty order.");
Status = OrderStatus.Submitted;
RaiseDomainEvent(new OrderSubmitted(Id, Total));
}
private void RecalculateTotal() =>
Total = _lines.Aggregate(
Money.Zero(Total.Currency),
(sum, line) => sum.Add(line.LineTotal));
}csharp
public sealed class Order : AggregateRoot<Guid>
{
public CustomerId CustomerId { get; private set; } = default!;
public OrderStatus Status { get; private set; }
public Money Total { get; private set; } = Money.Zero("USD");
private readonly List<OrderLine> _lines = [];
public IReadOnlyList<OrderLine> Lines => _lines.AsReadOnly();
private Order() { } // ORM构造函数
public static Order Create(CustomerId customerId)
{
var order = new Order(Guid.NewGuid())
{
CustomerId = customerId,
Status = OrderStatus.Draft
};
order.RaiseDomainEvent(new OrderCreated(order.Id, customerId));
return order;
}
public void AddLine(ProductId productId, int quantity, Money unitPrice)
{
if (Status != OrderStatus.Draft)
throw new DomainException("Cannot modify a non-draft order.");
if (quantity <= 0)
throw new DomainException("Quantity must be positive.");
var line = new OrderLine(productId, quantity, unitPrice);
_lines.Add(line);
RecalculateTotal();
}
public void Submit()
{
if (Status != OrderStatus.Draft)
throw new DomainException("Only draft orders can be submitted.");
if (_lines.Count == 0)
throw new DomainException("Cannot submit an empty order.");
Status = OrderStatus.Submitted;
RaiseDomainEvent(new OrderSubmitted(Id, Total));
}
private void RecalculateTotal() =>
Total = _lines.Aggregate(
Money.Zero(Total.Currency),
(sum, line) => sum.Add(line.LineTotal));
}Aggregate Design Rules
聚合设计规则
| Rule | Rationale |
|---|---|
| All mutations go through the aggregate root | Enforces invariants in one place |
| Reference other aggregates by ID only | Prevents cross-aggregate coupling; use |
| Keep aggregates small | Large aggregates cause lock contention and slow loads |
| One aggregate per transaction | Cross-aggregate changes use domain events and eventual consistency |
Expose collections as | Prevents external code from bypassing root methods to mutate children |
For the EF Core persistence implications of these rules (navigation properties, owned types, cascade behavior), see [skill:dotnet-efcore-architecture].
| 规则 | 原理 |
|---|---|
| 所有变更都通过聚合根操作 | 在单一位置强制业务不变量 |
| 仅通过ID引用其他聚合 | 避免跨聚合耦合;使用 |
| 保持聚合规模小 | 大聚合会导致锁竞争和加载缓慢 |
| 每个事务仅操作一个聚合 | 跨聚合变更使用领域事件和最终一致性 |
将集合暴露为 | 防止外部代码绕过根方法修改子对象 |
这些规则对EF Core持久化的影响(导航属性、owned类型、级联行为),参见 [skill:dotnet-efcore-architecture]。
Value Objects
值对象
Value objects have no identity -- they are defined by their attribute values. Two value objects with the same attributes are equal. In C#, and provide natural value semantics.
recordrecord struct值对象没有唯一标识——由其属性值定义,两个属性完全相同的值对象是相等的。在C#中,和天然支持值语义。
recordrecord structRecord-Based Value Objects
基于Record的值对象
csharp
// Simple value object -- wraps a primitive to enforce constraints
public sealed record CustomerId
{
public string Value { get; }
public CustomerId(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new DomainException("Customer ID cannot be empty.");
Value = value;
}
public override string ToString() => Value;
}
// Composite value object -- multiple properties with validation
public sealed record Address
{
public string Street { get; }
public string City { get; }
public string State { get; }
public string PostalCode { get; }
public string Country { get; }
public Address(string street, string city, string state,
string postalCode, string country)
{
if (string.IsNullOrWhiteSpace(street))
throw new DomainException("Street is required.");
if (string.IsNullOrWhiteSpace(city))
throw new DomainException("City is required.");
if (string.IsNullOrWhiteSpace(postalCode))
throw new DomainException("Postal code is required.");
Street = street;
City = city;
State = state;
PostalCode = postalCode;
Country = country;
}
}csharp
// 简单值对象——封装原生类型以强制约束
public sealed record CustomerId
{
public string Value { get; }
public CustomerId(string value)
{
if (string.IsNullOrWhiteSpace(value))
throw new DomainException("Customer ID cannot be empty.");
Value = value;
}
public override string ToString() => Value;
}
// 复合值对象——带校验的多属性结构
public sealed record Address
{
public string Street { get; }
public string City { get; }
public string State { get; }
public string PostalCode { get; }
public string Country { get; }
public Address(string street, string city, string state,
string postalCode, string country)
{
if (string.IsNullOrWhiteSpace(street))
throw new DomainException("Street is required.");
if (string.IsNullOrWhiteSpace(city))
throw new DomainException("City is required.");
if (string.IsNullOrWhiteSpace(postalCode))
throw new DomainException("Postal code is required.");
Street = street;
City = city;
State = state;
PostalCode = postalCode;
Country = country;
}
}Money Value Object
金额值对象
Money is the canonical example of a multi-field value object with behavior:
csharp
public sealed record Money
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
if (string.IsNullOrWhiteSpace(currency))
throw new DomainException("Currency is required.");
Amount = amount;
Currency = currency.ToUpperInvariant();
}
public static Money Zero(string currency) => new(0m, currency);
public Money Add(Money other)
{
EnsureSameCurrency(other);
return new Money(Amount + other.Amount, Currency);
}
public Money Subtract(Money other)
{
EnsureSameCurrency(other);
return new Money(Amount - other.Amount, Currency);
}
public Money Multiply(int quantity) =>
new(Amount * quantity, Currency);
public Money Multiply(decimal factor) =>
new(Amount * factor, Currency);
private void EnsureSameCurrency(Money other)
{
if (Currency != other.Currency)
throw new DomainException(
$"Cannot operate on {Currency} and {other.Currency}.");
}
public override string ToString() => $"{Amount:F2} {Currency}";
}金额是带行为的多字段值对象的典型示例:
csharp
public sealed record Money
{
public decimal Amount { get; }
public string Currency { get; }
public Money(decimal amount, string currency)
{
if (string.IsNullOrWhiteSpace(currency))
throw new DomainException("Currency is required.");
Amount = amount;
Currency = currency.ToUpperInvariant();
}
public static Money Zero(string currency) => new(0m, currency);
public Money Add(Money other)
{
EnsureSameCurrency(other);
return new Money(Amount + other.Amount, Currency);
}
public Money Subtract(Money other)
{
EnsureSameCurrency(other);
return new Money(Amount - other.Amount, Currency);
}
public Money Multiply(int quantity) =>
new(Amount * quantity, Currency);
public Money Multiply(decimal factor) =>
new(Amount * factor, Currency);
private void EnsureSameCurrency(Money other)
{
if (Currency != other.Currency)
throw new DomainException(
$"Cannot operate on {Currency} and {other.Currency}.");
}
public override string ToString() => $"{Amount:F2} {Currency}";
}Value Object EF Core Mapping
值对象EF Core映射
Map value objects using owned types or value conversions (implementation in [skill:dotnet-efcore-architecture]):
csharp
// Owned type -- maps to columns in the parent table
builder.OwnsOne(o => o.Total, money =>
{
money.Property(m => m.Amount).HasColumnName("TotalAmount");
money.Property(m => m.Currency).HasColumnName("TotalCurrency")
.HasMaxLength(3);
});
// Value conversion -- single-property value objects
builder.Property(o => o.CustomerId)
.HasConversion(
id => id.Value,
value => new CustomerId(value))
.HasMaxLength(50);使用owned类型或值转换器映射值对象(实现方式参见 [skill:dotnet-efcore-architecture]):
csharp
// Owned类型——映射到父表的列
builder.OwnsOne(o => o.Total, money =>
{
money.Property(m => m.Amount).HasColumnName("TotalAmount");
money.Property(m => m.Currency).HasColumnName("TotalCurrency")
.HasMaxLength(3);
});
// 值转换器——单属性值对象
builder.Property(o => o.CustomerId)
.HasConversion(
id => id.Value,
value => new CustomerId(value))
.HasMaxLength(50);When to Use Value Objects
何时使用值对象
| Use value object | Use primitive |
|---|---|
| Domain concept with constraints (email, money, quantity) | Infrastructure IDs with no domain rules (correlation IDs, trace IDs) |
| Multiple properties that form a unit (address, date range) | Single value with no validation needed |
| Need to prevent primitive obsession in domain methods | Simple DTO fields at API boundary |
| 使用值对象 | 使用原生类型 |
|---|---|
| 带约束的领域概念(邮箱、金额、数量) | 无领域规则的基础设施ID(关联ID、追踪ID) |
| 构成整体的多个属性(地址、日期范围) | 无需校验的单一值 |
| 需要避免领域方法中的原生类型痴迷问题 | API边界的简单DTO字段 |
Domain Events
领域事件
Domain events represent something meaningful that happened in the domain. They enable loose coupling between aggregates and trigger side effects (sending emails, updating read models, publishing integration events).
领域事件代表领域内发生的有意义的事件,可实现聚合间的松耦合,触发副作用(发送邮件、更新读模型、发布集成事件)。
Event Contracts
事件契约
csharp
// Marker interface for all domain events
public interface IDomainEvent
{
Guid EventId { get; }
DateTimeOffset OccurredAt { get; }
}
// Base record for convenience
public abstract record DomainEventBase : IDomainEvent
{
public Guid EventId { get; } = Guid.NewGuid();
public DateTimeOffset OccurredAt { get; } = DateTimeOffset.UtcNow;
}
// Concrete events
public sealed record OrderCreated(
Guid OrderId, CustomerId CustomerId) : DomainEventBase;
public sealed record OrderSubmitted(
Guid OrderId, Money Total) : DomainEventBase;
public sealed record OrderCancelled(
Guid OrderId, string Reason) : DomainEventBase;csharp
// 所有领域事件的标记接口
public interface IDomainEvent
{
Guid EventId { get; }
DateTimeOffset OccurredAt { get; }
}
// 便捷基类record
public abstract record DomainEventBase : IDomainEvent
{
public Guid EventId { get; } = Guid.NewGuid();
public DateTimeOffset OccurredAt { get; } = DateTimeOffset.UtcNow;
}
// 具体事件
public sealed record OrderCreated(
Guid OrderId, CustomerId CustomerId) : DomainEventBase;
public sealed record OrderSubmitted(
Guid OrderId, Money Total) : DomainEventBase;
public sealed record OrderCancelled(
Guid OrderId, string Reason) : DomainEventBase;Dispatching Domain Events
领域事件分发
Dispatch events after succeeds to ensure the aggregate state is persisted before side effects execute:
SaveChangesAsynccsharp
public sealed class DomainEventDispatcher(
IServiceProvider serviceProvider)
{
public async Task DispatchAsync(
IEnumerable<IDomainEvent> events,
CancellationToken ct)
{
foreach (var domainEvent in events)
{
var handlerType = typeof(IDomainEventHandler<>)
.MakeGenericType(domainEvent.GetType());
var handlers = serviceProvider.GetServices(handlerType);
foreach (var handler in handlers)
{
await ((dynamic)handler).HandleAsync(
(dynamic)domainEvent, ct);
}
}
}
}
// Note: The (dynamic) dispatch pattern is simple but not AOT-compatible.
// For Native AOT scenarios, use a source-generated or dictionary-based
// dispatcher. See [skill:dotnet-native-aot] for AOT constraints.
// Handler interface
public interface IDomainEventHandler<in TEvent>
where TEvent : IDomainEvent
{
Task HandleAsync(TEvent domainEvent, CancellationToken ct);
}在执行成功后再分发事件,确保副作用执行前聚合状态已持久化:
SaveChangesAsynccsharp
public sealed class DomainEventDispatcher(
IServiceProvider serviceProvider)
{
public async Task DispatchAsync(
IEnumerable<IDomainEvent> events,
CancellationToken ct)
{
foreach (var domainEvent in events)
{
var handlerType = typeof(IDomainEventHandler<>)
.MakeGenericType(domainEvent.GetType());
var handlers = serviceProvider.GetServices(handlerType);
foreach (var handler in handlers)
{
await ((dynamic)handler).HandleAsync(
(dynamic)domainEvent, ct);
}
}
}
}
// 注意:(dynamic)分发模式简单但不兼容AOT。
// 对于Native AOT场景,使用源码生成或基于字典的分发器。AOT约束参见 [skill:dotnet-native-aot]。
// 处理器接口
public interface IDomainEventHandler<in TEvent>
where TEvent : IDomainEvent
{
Task HandleAsync(TEvent domainEvent, CancellationToken ct);
}Saving with Event Dispatch
带事件分发的保存操作
Use an EF Core or a wrapper to dispatch events after save:
SaveChangesInterceptorcsharp
public sealed class EventDispatchingSaveChangesInterceptor(
DomainEventDispatcher dispatcher)
: SaveChangesInterceptor
{
public override async ValueTask<int> SavedChangesAsync(
SaveChangesCompletedEventData eventData,
int result,
CancellationToken ct)
{
if (eventData.Context is not null)
{
var aggregates = eventData.Context.ChangeTracker
.Entries<AggregateRoot<Guid>>()
.Where(e => e.Entity.DomainEvents.Count > 0)
.Select(e => e.Entity)
.ToList();
var events = aggregates
.SelectMany(a => a.DomainEvents)
.ToList();
foreach (var aggregate in aggregates)
{
aggregate.ClearDomainEvents();
}
await dispatcher.DispatchAsync(events, ct);
}
return result;
}
}使用EF Core的或包装类,在保存成功后分发事件:
SaveChangesInterceptorcsharp
public sealed class EventDispatchingSaveChangesInterceptor(
DomainEventDispatcher dispatcher)
: SaveChangesInterceptor
{
public override async ValueTask<int> SavedChangesAsync(
SaveChangesCompletedEventData eventData,
int result,
CancellationToken ct)
{
if (eventData.Context is not null)
{
var aggregates = eventData.Context.ChangeTracker
.Entries<AggregateRoot<Guid>>()
.Where(e => e.Entity.DomainEvents.Count > 0)
.Select(e => e.Entity)
.ToList();
var events = aggregates
.SelectMany(a => a.DomainEvents)
.ToList();
foreach (var aggregate in aggregates)
{
aggregate.ClearDomainEvents();
}
await dispatcher.DispatchAsync(events, ct);
}
return result;
}
}Domain Events vs Integration Events
领域事件 vs 集成事件
| Aspect | Domain Event | Integration Event |
|---|---|---|
| Scope | Within a bounded context | Across bounded contexts / services |
| Transport | In-process (dispatcher) | Message broker (Service Bus, RabbitMQ) |
| Coupling | References domain types | Uses primitive/DTO types only |
| Reliability | Same transaction scope | At-least-once with idempotent consumers |
| Example | | |
A domain event handler may publish an integration event to a message broker. See [skill:dotnet-messaging-patterns] for integration event infrastructure.
csharp
// Domain event handler that publishes an integration event
public sealed class OrderSubmittedHandler(
IPublishEndpoint publishEndpoint)
: IDomainEventHandler<OrderSubmitted>
{
public async Task HandleAsync(
OrderSubmitted domainEvent, CancellationToken ct)
{
// Map domain event to integration event (no domain types)
await publishEndpoint.Publish(
new OrderSubmittedIntegration(
domainEvent.OrderId,
domainEvent.Total.Amount,
domainEvent.Total.Currency),
ct);
}
}| 维度 | 领域事件 | 集成事件 |
|---|---|---|
| 作用范围 | 限界上下文内部 | 跨限界上下文/服务 |
| 传输方式 | 进程内(分发器) | 消息代理(Service Bus、RabbitMQ) |
| 耦合度 | 引用领域类型 | 仅使用原生类型/DTO |
| 可靠性 | 同事务范围 | 至少一次投递 + 幂等消费者 |
| 示例 | | |
领域事件处理器可以向消息代理发布集成事件,集成事件基础设施参见 [skill:dotnet-messaging-patterns]。
csharp
// 发布集成事件的领域事件处理器
public sealed class OrderSubmittedHandler(
IPublishEndpoint publishEndpoint)
: IDomainEventHandler<OrderSubmitted>
{
public async Task HandleAsync(
OrderSubmitted domainEvent, CancellationToken ct)
{
// 将领域事件映射为集成事件(无领域类型)
await publishEndpoint.Publish(
new OrderSubmittedIntegration(
domainEvent.OrderId,
domainEvent.Total.Amount,
domainEvent.Total.Currency),
ct);
}
}Rich vs Anemic Domain Models
富领域模型 vs 贫血领域模型
Rich Domain Model
富领域模型
Business logic lives inside the domain entities. Methods enforce invariants and return meaningful results:
csharp
public sealed class ShoppingCart : AggregateRoot<Guid>
{
private readonly List<CartItem> _items = [];
public IReadOnlyList<CartItem> Items => _items.AsReadOnly();
public void AddItem(ProductId productId, int quantity, Money unitPrice)
{
var existing = _items.Find(i => i.ProductId == productId);
if (existing is not null)
{
existing.IncreaseQuantity(quantity);
}
else
{
_items.Add(new CartItem(productId, quantity, unitPrice));
}
}
public void RemoveItem(ProductId productId)
{
var item = _items.Find(i => i.ProductId == productId)
?? throw new DomainException(
$"Product {productId} not in cart.");
_items.Remove(item);
}
public Money GetTotal(string currency) =>
_items.Aggregate(
Money.Zero(currency),
(sum, item) => sum.Add(item.LineTotal));
}业务逻辑位于领域实体内部,方法强制业务不变量并返回有意义的结果:
csharp
public sealed class ShoppingCart : AggregateRoot<Guid>
{
private readonly List<CartItem> _items = [];
public IReadOnlyList<CartItem> Items => _items.AsReadOnly();
public void AddItem(ProductId productId, int quantity, Money unitPrice)
{
var existing = _items.Find(i => i.ProductId == productId);
if (existing is not null)
{
existing.IncreaseQuantity(quantity);
}
else
{
_items.Add(new CartItem(productId, quantity, unitPrice));
}
}
public void RemoveItem(ProductId productId)
{
var item = _items.Find(i => i.ProductId == productId)
?? throw new DomainException(
$"Product {productId} not in cart.");
_items.Remove(item);
}
public Money GetTotal(string currency) =>
_items.Aggregate(
Money.Zero(currency),
(sum, item) => sum.Add(item.LineTotal));
}Anemic Domain Model (Anti-Pattern)
贫血领域模型(反模式)
Entities are data bags with public setters. Business logic lives in external services:
csharp
// ANTI-PATTERN: Entity is just a data container
public class ShoppingCart
{
public Guid Id { get; set; }
public List<CartItem> Items { get; set; } = [];
}
// All logic lives here -- the entity has no behavior
public class ShoppingCartService
{
public void AddItem(ShoppingCart cart, string productId,
int quantity, decimal unitPrice)
{
var existing = cart.Items.Find(i => i.ProductId == productId);
if (existing != null)
existing.Quantity += quantity;
else
cart.Items.Add(new CartItem { ... });
}
}实体是带公共setter的数据包,业务逻辑位于外部服务中:
csharp
// 反模式:实体仅作为数据容器
public class ShoppingCart
{
public Guid Id { get; set; }
public List<CartItem> Items { get; set; } = [];
}
// 所有逻辑都在这里——实体没有任何行为
public class ShoppingCartService
{
public void AddItem(ShoppingCart cart, string productId,
int quantity, decimal unitPrice)
{
var existing = cart.Items.Find(i => i.ProductId == productId);
if (existing != null)
existing.Quantity += quantity;
else
cart.Items.Add(new CartItem { ... });
}
}Decision Guide
决策指南
| Factor | Rich model | Anemic model |
|---|---|---|
| Complex invariants | Enforced in entity | Scattered across services |
| Testability | Test entity behavior directly | Test service + entity together |
| Discoverability | Methods on entity show capabilities | Must find the right service class |
| Persistence coupling | Requires ORM-friendly private setters | Simple property mapping |
| Team familiarity | DDD experience required | Familiar to most developers |
Recommendation: Start with a rich model for aggregates with complex business rules. Anemic models are acceptable for simple CRUD entities where the domain logic is minimal (e.g., reference data, configuration records).
| 因素 | 富模型 | 贫血模型 |
|---|---|---|
| 复杂不变量 | 在实体内强制 | 分散在各个服务中 |
| 可测试性 | 直接测试实体行为 | 需要同时测试服务和实体 |
| 可发现性 | 实体上的方法展示其能力 | 需要找到对应的服务类 |
| 持久化耦合 | 需要ORM友好的私有setter | 简单的属性映射 |
| 团队熟悉度 | 需要DDD经验 | 大多数开发者都熟悉 |
建议: 对于带有复杂业务规则的聚合,从富模型开始开发。对于领域逻辑极少的简单CRUD实体(比如参考数据、配置记录),贫血模型是可接受的。
Domain Services
领域服务
Domain services encapsulate business logic that does not naturally belong to a single entity or value object. They operate on domain types and enforce cross-aggregate rules.
csharp
public sealed class PricingService
{
public Money CalculateDiscount(
Order order,
CustomerTier tier,
IReadOnlyList<PromotionRule> activePromotions)
{
var discount = Money.Zero(order.Total.Currency);
// Tier-based discount
discount = tier switch
{
CustomerTier.Gold => discount.Add(
order.Total.Multiply(0.10m)),
CustomerTier.Platinum => discount.Add(
order.Total.Multiply(0.15m)),
_ => discount
};
// Promotion-based discounts
foreach (var promo in activePromotions)
{
if (promo.AppliesTo(order))
{
discount = discount.Add(promo.Calculate(order));
}
}
return discount;
}
}领域服务封装不属于单个实体或值对象的业务逻辑,操作领域类型并强制跨聚合规则。
csharp
public sealed class PricingService
{
public Money CalculateDiscount(
Order order,
CustomerTier tier,
IReadOnlyList<PromotionRule> activePromotions)
{
var discount = Money.Zero(order.Total.Currency);
// 基于客户等级的折扣
discount = tier switch
{
CustomerTier.Gold => discount.Add(
order.Total.Multiply(0.10m)),
CustomerTier.Platinum => discount.Add(
order.Total.Multiply(0.15m)),
_ => discount
};
// 基于活动的折扣
foreach (var promo in activePromotions)
{
if (promo.AppliesTo(order))
{
discount = discount.Add(promo.Calculate(order));
}
}
return discount;
}
}When to Use Domain Services
何时使用领域服务
- Logic requires data from multiple aggregates that should not reference each other
- A business rule does not belong to any single entity (e.g., pricing across products and customer tiers)
- External policy or configuration drives the logic (e.g., tax calculation rules)
Domain services should remain pure -- no infrastructure dependencies. If the logic needs a database or external API, place it in an application service that calls the domain service with pre-loaded data.
- 逻辑需要来自多个互不引用的聚合的数据
- 业务规则不属于任何单个实体(比如跨产品和客户等级的定价逻辑)
- 逻辑由外部策略或配置驱动(比如计税规则)
领域服务应保持纯函数特性——无基础设施依赖。如果逻辑需要数据库或外部API,将其放在应用服务中,由应用服务预加载数据后调用领域服务。
Repository Contracts
仓储契约
Repository interfaces belong in the domain layer and express aggregate loading and saving semantics. Implementation details (EF Core, Dapper) live in the infrastructure layer.
csharp
// Domain layer -- defines the contract
public interface IOrderRepository
{
Task<Order?> FindByIdAsync(Guid id, CancellationToken ct);
Task AddAsync(Order order, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
// Domain layer -- unit of work abstraction (optional)
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken ct);
}For EF Core repository implementations, see [skill:dotnet-efcore-architecture].
仓储接口属于领域层,定义聚合的加载和保存语义。实现细节(EF Core、Dapper)位于基础设施层。
csharp
// 领域层——定义契约
public interface IOrderRepository
{
Task<Order?> FindByIdAsync(Guid id, CancellationToken ct);
Task AddAsync(Order order, CancellationToken ct);
Task SaveChangesAsync(CancellationToken ct);
}
// 领域层——工作单元抽象(可选)
public interface IUnitOfWork
{
Task<int> SaveChangesAsync(CancellationToken ct);
}EF Core仓储实现参见 [skill:dotnet-efcore-architecture]。
Repository Design Rules
仓储设计规则
| Rule | Rationale |
|---|---|
| One repository per aggregate root | Child entities are accessed through the root |
No | Prevents persistence concerns from leaking into domain |
No generic | Cannot express aggregate-specific loading rules |
| Return domain types, not DTOs | Repositories serve the domain; read models use projections |
Include | Required for proper cancellation propagation |
| 规则 | 原理 |
|---|---|
| 每个聚合根对应一个仓储 | 子实体通过聚合根访问 |
不返回 | 避免持久化逻辑泄露到领域层 |
不使用泛型 | 无法表达聚合特定的加载规则 |
| 返回领域类型而非DTO | 仓储为领域层服务;读模型使用投影 |
所有异步方法都包含 | 支持正确的取消传播 |
Domain Exceptions
领域异常
Use domain-specific exceptions to signal invariant violations. This separates domain errors from infrastructure errors:
csharp
public class DomainException : Exception
{
public DomainException(string message) : base(message) { }
public DomainException(string message, Exception inner)
: base(message, inner) { }
}
// Specific domain exceptions for different invariant violations
public sealed class InsufficientStockException(
ProductId productId, int requested, int available)
: DomainException(
$"Insufficient stock for {productId}: " +
$"requested {requested}, available {available}")
{
public ProductId ProductId => productId;
public int Requested => requested;
public int Available => available;
}Map domain exceptions to HTTP responses at the API boundary (e.g., to 422 Unprocessable Entity). Do not let infrastructure concerns like HTTP status codes leak into the domain layer.
DomainException使用领域特定的异常来标记业务不变量违反,将领域错误和基础设施错误区分开:
csharp
public class DomainException : Exception
{
public DomainException(string message) : base(message) { }
public DomainException(string message, Exception inner)
: base(message, inner) { }
}
// 针对不同不变量违反的特定领域异常
public sealed class InsufficientStockException(
ProductId productId, int requested, int available)
: DomainException(
$"Insufficient stock for {productId}: " +
$"requested {requested}, available {available}")
{
public ProductId ProductId => productId;
public int Requested => requested;
public int Available => available;
}在API边界将领域异常映射为HTTP响应(比如映射为422 Unprocessable Entity)。不要让HTTP状态码等基础设施逻辑泄露到领域层。
DomainExceptionAgent Gotchas
常见陷阱
- Do not expose public setters on aggregate properties -- all state changes must go through methods on the aggregate root that enforce invariants. Use or
private setfor properties.init - Do not create navigation properties between aggregate roots -- reference other aggregates by ID value objects (e.g., ) not by entity navigation. Cross-aggregate navigation breaks bounded context isolation.
CustomerId - Do not dispatch domain events inside the transaction -- dispatch after succeeds. Dispatching before save means side effects fire even if the save fails.
SaveChangesAsync - Do not use domain types in integration events -- integration events cross bounded context boundaries and must use primitives or DTOs. Domain type changes would break other services.
- Do not put validation logic only in the API layer -- domain invariants belong in the domain model. API validation ([skill:dotnet-validation-patterns]) catches malformed input; domain validation enforces business rules.
- Do not create anemic entities with public properties -- expose collections as
List<T>and provide mutation methods on the aggregate root that enforce business rules.IReadOnlyList<T> - Do not inject infrastructure services into domain entities -- entities should be pure C# objects. Use domain services for logic that needs external data, and application services for infrastructure orchestration.
- 不要在聚合属性上暴露公共setter——所有状态变更必须通过聚合根上强制业务不变量的方法完成,属性使用或
private set。init - 不要在聚合根之间创建导航属性——通过ID值对象引用其他聚合(比如)而非实体导航,跨聚合导航会破坏限界上下文隔离。
CustomerId - 不要在事务内部分发领域事件——在执行成功后再分发,保存前分发会导致即使保存失败副作用也已执行。
SaveChangesAsync - 不要在集成事件中使用领域类型——集成事件跨限界上下文边界,必须使用原生类型或DTO,领域类型变更会破坏其他服务。
- 不要只在API层做校验逻辑——领域不变量属于领域模型,API校验([skill:dotnet-validation-patterns])捕获格式错误的输入,领域校验强制业务规则。
- 不要创建带公共属性的贫血实体——将集合暴露为
List<T>,并在聚合根上提供强制业务规则的变更方法。IReadOnlyList<T> - 不要向领域实体注入基础设施服务——实体应该是纯C#对象,需要外部数据的逻辑使用领域服务,基础设施编排使用应用服务。