Repository navigation
Getting Started
This guide walks you through installing the packages and wiring up a complete event sourcing stack — from handling your first command to projecting events into a read model.
Install the core package and a storage integration. Pick either KurrentDB or MSSP.
dotnet add package Aggregates --prerelease
dotnet add package Aggregates.MSSP --prerelease # or Aggregates.KurrentDB
For sagas, policies, or projections add the matching extension packages:
dotnet add package Aggregates.Sagas --prerelease
dotnet add package Aggregates.Sagas.MSSP --prerelease # or Aggregates.Sagas.KurrentDB
dotnet add package Aggregates.Policies --prerelease
dotnet add package Aggregates.Policies.MSSP --prerelease
dotnet add package Aggregates.Projections --prerelease
dotnet add package Aggregates.Projections.MSSP --prerelease
dotnet add package Aggregates.Projections.Sql --prerelease # optional: SQL commit helper
Implement IState<TState, TEvent> on your state object. Initial is the empty starting state. Apply is a pure function that produces the next state from the current one and an event.
record ShoppingCartState(ImmutableDictionary<string, int> Items)
: IState<ShoppingCartState, IShoppingCartEvent> {
public static ShoppingCartState Initial =>
new(ImmutableDictionary<string, int>.Empty);
public ShoppingCartState Apply(IShoppingCartEvent @event) => @event switch {
ItemAdded e => this with { Items = Items.SetItem(e.ItemId,
Items.GetValueOrDefault(e.ItemId) + e.Quantity) },
ItemRemoved e => this with { Items = Items.SetItem(e.ItemId,
Items[e.ItemId] - e.Quantity) },
_ => this
};
}Events are plain records. Decorate them with [EventContract] to control the stored type name and enable schema evolution:
[EventContract("ItemAdded", namespace: "ShoppingCart")]
record ItemAdded(string ItemId, int Quantity) : IShoppingCartEvent;
[EventContract("ItemRemoved", namespace: "ShoppingCart")]
record ItemRemoved(string ItemId, int Quantity) : IShoppingCartEvent;The stored type name becomes ShoppingCart.ItemAdded@v1. Omitting the attribute causes the library to fall back to the .NET type name.
Implement ICommand<TState, TEvent>. The Id property identifies the target aggregate. ProgressAsync validates the state and yields the resulting events:
record AddItem(AggregateIdentifier Id, string ItemId, int Quantity)
: ICommand<ShoppingCartState, IShoppingCartEvent> {
public async IAsyncEnumerable<IShoppingCartEvent> ProgressAsync(
ShoppingCartState state,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (Quantity <= 0) throw new ArgumentOutOfRangeException(nameof(Quantity));
yield return new ItemAdded(ItemId, Quantity);
}
}Inject ICommandHandler<TCommand> wherever you need it. The library auto-registers a handler for each command discovered by ScanAssemblies:
class ShoppingCartController(ICommandHandler<AddItem> handler) : ControllerBase {
[HttpPost("{id:guid}")]
public async Task<IActionResult> Post(Guid id, [FromBody] AddItemRequest req, CancellationToken ct) {
await handler.HandleAsync(new AddItem(id.ToString(), req.ItemId, req.Quantity), ct);
return Ok();
}
}To register an explicit set of commands instead of everything in an assembly, use ScanTypes(typeof(AddItem), typeof(RemoveItem)). AddSagas, AddPolicies and AddProjections offer the same choice.
Use EventTypeRegistry to translate between CLR types and the stable event names stored in the event store. Build it once at startup by scanning the assembly (or assemblies) that contain your event records:
var registry = EventTypeRegistry.FromAssemblies(typeof(ItemAdded).Assembly);Then pass it to the storage integration options:
// MSSP
services
.AddAggregates(o => o.ScanAssemblies(typeof(AddItem).Assembly))
.AddMssp(o => {
o.Serialize = evt => new EventData(
registry.GetTypeName(evt),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null;
});
// KurrentDB
services
.AddAggregates(o => o.ScanAssemblies(typeof(AddItem).Assembly))
.AddKurrentDb(o => {
o.Serialize = evt => new SerializedEvent(
registry.GetTypeName(evt),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null;
});IMsspClient (or KurrentDBClient) must already be registered in the container before calling AddMssp / AddKurrentDb.
TryGetType returns false for unknown type names — events from another service, or event types that have been removed. The null returned from the Deserialize delegate signals the infrastructure to skip that event.
Also register the registry in the container. Sagas, policies and projections then receive only the event types they handle: the event store filters the rest out before they are sent or deserialised.
services.AddSingleton(registry);Without it, every subscription reads and deserialises every event in the store. See Event-type filter.
When an event's shape changes between versions, use IUpgradeEvent<TOld, TNew> and bump the [EventContract] version:
// Old version (v1) — still in the event store
record ItemAddedV1(string ItemId, int Quantity);
// Upgrader
class ItemAddedUpgrader : IUpgradeEvent<ItemAddedV1, ItemAdded> {
public ItemAdded Upgrade(ItemAddedV1 old) =>
new(old.ItemId, old.Quantity, Unit: "pcs"); // new field with default
}
// Current version (v2)
[EventContract("ItemAdded", version: 2, eventUpgrader: typeof(ItemAddedUpgrader), namespace: "ShoppingCart")]
record ItemAdded(string ItemId, int Quantity, string Unit) : IShoppingCartEvent;The integration package detects the stored version from the type name (ItemAdded@v1) and automatically upgrades the event before handing it to Apply.
A saga is a stateful process manager. It persists its own state in the event store and reacts to events by dispatching commands.
Same IState<TSagaState, TEvent> pattern as aggregates:
record OrderFulfillmentState(bool IsShipped)
: IState<OrderFulfillmentState, IOrderEvent> {
public static OrderFulfillmentState Initial => new(false);
public OrderFulfillmentState Apply(IOrderEvent @event) => @event switch {
OrderShipped => this with { IsShipped = true },
_ => this
};
}[SagaContract("OrderFulfillment", namespace: "Orders")]
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, IOrderEvent> {
public async IAsyncEnumerable<ICommand> ReactAsync(
OrderFulfillmentState state,
IOrderEvent @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (@event is OrderPlaced placed && !state.IsShipped)
yield return new ShipOrder(placed.OrderId);
}
}[SagaContract] assigns a stable identity to the saga's subscription: it names its checkpoint. The saga's state streams are named by the ids the resolver returns (step 3). Use startFromEnd: true to skip existing history on first run. A new contract version continues from the previous version's checkpoint; see Where a subscription starts.
services
.AddAggregates(o => o.ScanAssemblies(typeof(ShipOrder).Assembly))
.AddMssp(o => { /* serialization */ });
services
.AddAggregates()
.AddSagas(o => o
.ScanAssemblies(typeof(OrderFulfillmentSaga).Assembly)
.WithResolver<IOrderEvent>((_, metadata) =>
metadata.TryGetValue("SagaId", out var value) && value is object?[] ids
? ids.OfType<string>().Select(id => new AggregateIdentifier(id))
: []))
.AddMssp();WithResolver maps an event type to the saga instance(s) that should handle it. The two-parameter overload receives both the event and its stored metadata — useful when saga identifiers are carried in metadata rather than the event body. A single resolver registered for a base event interface covers all its subtypes. Sagas without a resolver are registered but never triggered. When several sagas react to the same event type, give each its own resolver with WithResolver<TSaga, TEvent>(...).
When the saga ID is a property on the event body rather than metadata, use the single-parameter overload:
.WithResolver<IOrderEvent>(e => e is OrderPlaced p ? [new AggregateIdentifier(p.OrderId)] : [])A saga can plan a command for later with SagaTimeout.At(due, command). Here, a reminder three days before a bill's due date and one on the due date itself:
[SagaContract("PaymentReminders", namespace: "Billing")]
class PaymentReminderSaga(BillingClock clock) : ISaga<PaymentReminderState, IPaymentEvent> {
public async IAsyncEnumerable<ICommand> ReactAsync(
PaymentReminderState state,
IPaymentEvent @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (@event is PaymentPlanned { DirectDebit: false } planned) {
yield return SagaTimeout.At(clock.StartOfDay(planned.DueDate.AddDays(-3)), new SendReminder(planned.PaymentId, planned.DueDate));
yield return SagaTimeout.At(clock.StartOfDay(planned.DueDate), new SendReminder(planned.PaymentId, planned.DueDate));
}
}
}When the due time has passed, the command runs like any other. A reminder can be stale by then: the bill was paid, or its due date moved and a new reminder was planned. The command decides, from the state of its aggregate:
[EventContract("SendReminder", namespace: "Billing")] // stored until it is due: give it a stable name
record SendReminder(AggregateIdentifier Id, DateOnly DueDate) : ICommand<PaymentState, IPaymentEvent> {
public async IAsyncEnumerable<IPaymentEvent> ProgressAsync(
PaymentState state,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (!state.Paid && state.DueDate == DueDate && !state.RemindedFor.Contains(DueDate))
yield return new ReminderSent(Id.Value, DueDate);
}
}- A due time in the past runs right away (a bill planned late).
- A timeout runs at least once, so the command must be idempotent; the check above does that too.
- The command waits in the store, so the serializer must know its type. Converting "the due date in the user's time zone" to an instant is the application's job.
Nothing else is needed: the saga's scheduler starts by itself when the saga requests its first timeout. See Saga timeouts for how they are stored, restarts, and what happens when a command type changes.
A policy is stateless — it reacts to an event and dispatches commands with no memory between invocations.
[PolicyContract("SendWelcomeEmail", namespace: "Users")]
class SendWelcomeEmailPolicy : IPolicy<UserRegistered> {
public async IAsyncEnumerable<ICommand> ReactAsync(
UserRegistered @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
yield return new SendEmail(@event.UserId, "Welcome!");
}
}services
.AddAggregates(o => o.ScanAssemblies(typeof(SendEmail).Assembly))
.AddMssp(o => { /* serialization */ });
services
.AddAggregates()
.AddPolicies(o => o.ScanAssemblies(typeof(SendWelcomeEmailPolicy).Assembly))
.AddMssp();A subscription hosted service is registered automatically for every scanned policy.
A projection reads the event stream and writes to an external read model (SQL database, search index, etc.).
[ProjectionContract("Orders", namespace: "ReadModels")]
class OrdersProjection(IDbConnectionFactory db) : IProjection<IOrdersEvent> {
public ValueTask<ICommit> ProjectAsync(
IOrdersEvent @event,
EventMetadata metadata,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<ICommit>(@event switch {
OrderPlaced e => Commit.Create().UseSql(db)
.Query("INSERT INTO orders (id, date) VALUES (@Id, @Date)",
new { e.Id, e.Date }),
OrderShipped e => Commit.Create().UseSql(db)
.Query("UPDATE orders SET shipped = 1 WHERE id = @Id",
new { e.Id }),
_ => Commit.Create()
});
}Commit.Create() starts an empty commit chain. .UseSql(db).Query(...) (from Aggregates.Projections.Sql) appends a SQL statement. The infrastructure calls CommitAsync after ProjectAsync returns.
services
.AddProjections(o => o.ScanAssemblies(typeof(OrdersProjection).Assembly))
.AddMssp();A subscription hosted service is registered for every scanned projection.