Class AggregateRoot<TKey>
Base class for event-sourced aggregates with strongly-typed keys.
public abstract class AggregateRoot<TKey> : IAggregateRoot<TKey>, IAggregateRoot, IAggregateSnapshotSupport where TKey : notnull
Type Parameters
TKeyThe type of the aggregate identifier.
- Inheritance
-
AggregateRoot<TKey>
- Implements
-
IAggregateRoot<TKey>
- Derived
- Inherited Members
Examples
public class OrderAggregate : AggregateRoot<Guid>
{
public OrderStatus Status { get; private set; }
protected override bool ApplyEventInternal(IDomainEvent @event) => @event switch
{
OrderCreated e => Apply(e),
OrderShipped e => Apply(e),
_ => false
};
private bool Apply(OrderCreated e)
{
Id = e.OrderId;
Status = OrderStatus.Created;
return true;
}
}
Remarks
This base class provides:
- Pattern-matching event application via ApplyEventInternal(IDomainEvent) (no reflection)
- Uncommitted events collection for persistence
- Version tracking for optimistic concurrency
- ETag-based optimistic concurrency support
- Snapshot support for performance optimization
- History replay via LoadFromHistory(IEnumerable<HistoricEvent>)
Derived classes can implement ApplyEventInternal(IDomainEvent) using explicit event-type dispatch. Execution time depends on the event handler's work.
Constructors
AggregateRoot()
Initializes a new instance of the AggregateRoot<TKey> class.
protected AggregateRoot()
AggregateRoot(TKey)
Initializes a new instance of the AggregateRoot<TKey> class with an identifier.
protected AggregateRoot(TKey id)
Parameters
idTKeyThe unique identifier of the aggregate.
Properties
AggregateType
Gets the type name of the aggregate for persistence.
public virtual string AggregateType { get; }
Property Value
- string
The type name of the aggregate for persistence.
ETag
Gets or sets the ETag for optimistic concurrency control.
public string? ETag { get; set; }
Property Value
- string
The ETag value representing the current state version, or null if not set. Used for detecting concurrent modifications when saving aggregates.
HasUncommittedEvents
Gets a value indicating whether the aggregate has uncommitted events.
public bool HasUncommittedEvents { get; }
Property Value
Id
Gets the strongly-typed unique identifier of the aggregate.
public TKey Id { get; protected set; }
Property Value
- TKey
The unique identifier of the aggregate.
Version
Gets the current version of the aggregate.
public long Version { get; protected set; }
Property Value
- long
The current version of the aggregate.
Methods
ApplyEvent(IDomainEvent)
Applies a historical event to rebuild state.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ApplyEvent(IDomainEvent eventData)
Parameters
eventDataIDomainEventThe event to apply.
ApplyEventInternal(IDomainEvent)
Applies the event's changes to the aggregate's state using pattern matching.
protected abstract bool ApplyEventInternal(IDomainEvent @event)
Parameters
eventIDomainEventThe domain event to apply.
Returns
- bool
true if the aggregate recognized and applied the event type; otherwise false. Returning false (a missing switch arm) causes the caller to throw UnhandledDomainEventException — an unrecognized event is refused, never silently ignored.
Remarks
Implement this method using a switch expression for optimal performance. The default arm returns false so an unhandled event fails loud:
protected override bool ApplyEventInternal(IDomainEvent @event) => @event switch
{
OrderCreated e => Apply(e),
OrderConfirmed e => Apply(e),
_ => false
};
Each Apply overload returns true.
ApplySnapshot(ISnapshot)
Applies a snapshot to restore aggregate state.
protected virtual void ApplySnapshot(ISnapshot snapshot)
Parameters
snapshotISnapshotThe snapshot to apply.
Remarks
Override this method to deserialize snapshot data and restore aggregate state. It must be overridden in lock-step with CreateSnapshot(): an aggregate that produces snapshots must also know how to consume them.
The base implementation is fail-closed. It throws NotSupportedException rather than silently no-op'ing, because reaching it means a snapshot was produced (only an overridden CreateSnapshot() can persist one) but ApplySnapshot(ISnapshot) was not overridden to consume it. Silently returning would load empty state and then stamp Version from the snapshot in LoadFromSnapshot(ISnapshot) — silent state corruption. Aggregates that do not support snapshots never reach this method, because their CreateSnapshot() also throws and so no snapshot is ever created to load.
Exceptions
- NotSupportedException
Always thrown by the base implementation, indicating ApplySnapshot(ISnapshot) was not overridden to match an overridden CreateSnapshot().
CreateSnapshot()
Creates a snapshot of the current aggregate state.
public virtual ISnapshot CreateSnapshot()
Returns
- ISnapshot
A snapshot representing the current state.
Remarks
This method may require runtime type inspection and dynamic code generation, which are not compatible with Native AOT compilation scenarios. Consider using source generation for snapshot creation in AOT-compiled applications.
GetService(Type)
Gets a service of the specified type from this aggregate.
public object? GetService(Type serviceType)
Parameters
serviceTypeTypeThe type of service to retrieve (e.g. IAggregateSnapshotSupport).
Returns
GetUncommittedEvents()
Gets the list of uncommitted events.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public IReadOnlyList<IDomainEvent> GetUncommittedEvents()
Returns
- IReadOnlyList<IDomainEvent>
The list of uncommitted events.
LoadFromHistory(IEnumerable<HistoricEvent>)
Loads the aggregate state from a history of events.
public void LoadFromHistory(IEnumerable<HistoricEvent> history)
Parameters
historyIEnumerable<HistoricEvent>The sequence of historical events to replay, each paired with the authoritative stream version the event store assigned to it.
Remarks
This method replays events to rebuild aggregate state without adding them to the uncommitted events collection. Use this for event sourcing replay. The version is read from the envelope rather than the event payload, so an event that does not carry its own position replays correctly.
LoadFromSnapshot(ISnapshot)
Loads the aggregate state from a snapshot.
public virtual void LoadFromSnapshot(ISnapshot snapshot)
Parameters
snapshotISnapshotThe snapshot to load from.
MarkEventsAsCommitted()
Marks all uncommitted events as committed.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void MarkEventsAsCommitted()
RaiseEvent(IDomainEvent)
Raises a new event, applies it to update state, and adds it to uncommitted events.
protected void RaiseEvent(IDomainEvent @event)
Parameters
eventIDomainEventThe event to raise.
Remarks
This method:
- Applies the event via ApplyEventInternal(IDomainEvent) to update aggregate state
- Adds the event to the uncommitted events collection
Note: Version is NOT incremented here. Version is incremented in MarkEventsAsCommitted() when events are persisted.