Table of Contents

Class AggregateRoot<TAggregate, TKey>

Namespace
Excalibur.Domain.Model
Assembly
Excalibur.Domain.dll

Convenience base class for event-sourced aggregates that enables type inference for AddRepository<TAggregate, TKey>() zero-argument registration.

public abstract class AggregateRoot<TAggregate, TKey> : AggregateRoot<TKey>, IAggregateSnapshotSupport, IAggregateRoot<TAggregate, TKey>, IAggregateRoot<TKey>, IAggregateRoot where TAggregate : AggregateRoot<TAggregate, TKey>, new() where TKey : notnull

Type Parameters

TAggregate

The concrete aggregate type (CRTP self-type).

TKey

The type of the aggregate identifier.

Inheritance
AggregateRoot<TAggregate, TKey>
Implements
IAggregateRoot<TAggregate, TKey>
Inherited Members

Remarks

Deriving from this class automatically implements IAggregateRoot<TAggregate, TKey>, requiring only the static abstract factory methods:

public class OrderAggregate : AggregateRoot<OrderAggregate, Guid>
{
    public static OrderAggregate Create(Guid id) => new() { Id = id };
public static OrderAggregate FromEvents(Guid id, IEnumerable<HistoricEvent> events)
{
    var aggregate = Create(id);
    aggregate.LoadFromHistory(events);
    return aggregate;
}

protected override bool ApplyEventInternal(IDomainEvent @event) => @event switch
{
    OrderCreated e => Apply(e),
    _ => false
};

}

This enables zero-argument repository registration:

builder.AddRepository<OrderAggregate, Guid>();

Without this base class, consumers must independently implement IAggregateRoot<TAggregate, TKey> on their aggregate class.

Constructors

AggregateRoot()

Initializes a new instance of the AggregateRoot<TAggregate, TKey> class.

protected AggregateRoot()

AggregateRoot(TKey)

Initializes a new instance of the AggregateRoot<TAggregate, TKey> class with an identifier.

protected AggregateRoot(TKey id)

Parameters

id TKey

The unique identifier of the aggregate.

Methods

Create(TKey)

Creates a new instance of the aggregate with the specified identifier.

public static TAggregate Create(TKey id)

Parameters

id TKey

The unique identifier for the aggregate.

Returns

TAggregate

A new aggregate instance with its Id set.

Remarks

This default implementation uses the parameterless constructor and sets the Id. Override in the concrete aggregate if custom initialization is needed.

FromEvents(TKey, IEnumerable<HistoricEvent>)

Rebuilds an aggregate from a stream of historical events.

public static TAggregate FromEvents(TKey id, IEnumerable<HistoricEvent> events)

Parameters

id TKey

The unique identifier for the aggregate.

events IEnumerable<HistoricEvent>

The stream of events to replay.

Returns

TAggregate

The aggregate rebuilt from the events.