Skip to content

API Reference

Wouter Naessens edited this page May 23, 2026 · 32 revisions

API Reference

Complete reference for all public types, interfaces, and attributes in the Aggregates library.


Aggregates (core)

IState<TState, TEvent>

The state of an aggregate or saga. Implement this on your state record.

public interface IState<out TState, in TEvent> where TState : IState<TState, TEvent> {
    static abstract TState Initial { get; }
    TState Apply(TEvent @event);
}
Member Description
Initial The empty starting state. Static abstract — defined on the implementing type.
Apply(event) Applies the event and returns the next state. Must always succeed.

ICommand

Marker interface. All commands implement this.

public interface ICommand;

ICommand<TState, TEvent>

A command that targets an aggregate and produces events.

public interface ICommand<in TState, out TEvent> : ICommand
    where TState : IState<TState, TEvent> {

    AggregateIdentifier Id { get; }
    IAsyncEnumerable<TEvent> ProgressAsync(TState state, CancellationToken cancellationToken = default);
}
Member Description
Id Identifies the target aggregate.
ProgressAsync Validates the current state and yields events. Allowed to throw; this is the domain rule enforcement point.

ICommandHandler<TCommand>

Handles a command end-to-end: loads the aggregate, runs ProgressAsync, and persists the result. Registered automatically; inject this into your application code.

public interface ICommandHandler<in TCommand> where TCommand : ICommand {
    ValueTask HandleAsync(TCommand command, CancellationToken cancellationToken = default);
}

ICommandDispatcher

Dispatches a command without knowing its concrete type. Useful when the command type is only known at runtime (e.g. from a saga).

public interface ICommandDispatcher {
    ValueTask DispatchAsync(ICommand command, CancellationToken cancellationToken = default);
}

IAggregateRoot

Internal tracking interface for the aggregate root. You do not implement this directly — EntityRoot<TState, TEvent> does.

public interface IAggregateRoot {
    AggregateVersion Version { get; }
    IEnumerable<object> GetChanges();
}

EntityRoot<TState, TEvent>

The concrete aggregate root. Maintains state, tracks pending changes, and applies commands.

public sealed class EntityRoot<TState, TEvent>(AggregateVersion version, TState? state = default)
    : IAggregateRoot
    where TState : IState<TState, TEvent> {

    public TState State { get; }
    public AggregateVersion Version { get; }
    public IEnumerable<object> GetChanges();
    public ValueTask AcceptAsync<TCommand>(TCommand command, CancellationToken cancellationToken = default)
        where TCommand : ICommand<TState, TEvent>;
}

AggregateIdentifier

A string-based identifier for an aggregate or saga.

public record struct AggregateIdentifier(string Value) {
    public static implicit operator AggregateIdentifier(string value);
    public override string ToString();
}

AggregateVersion

The revision of an aggregate at load time. Used for optimistic concurrency.

public record struct AggregateVersion {
    public static explicit operator long(AggregateVersion version);
    public static explicit operator AggregateVersion(long version);
}

ConcurrencyException

Thrown when a commit is rejected because the aggregate was modified concurrently.

public class ConcurrencyException(
    AggregateIdentifier identifier,
    AggregateVersion expectedVersion,
    AggregateVersion actualVersion) : Exception {

    public AggregateIdentifier Identifier { get; }
    public AggregateVersion ExpectedVersion { get; }
    public AggregateVersion ActualVersion { get; }
}

RetryCommandHandler catches this automatically and retries up to three times.


EventContractAttribute

Maps a .NET event type to a stable event store type name and optionally wires an upgrader.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class EventContractAttribute(
    string name,
    int version = 1,
    Type? eventUpgrader = null,
    string? @namespace = null) : Attribute {

    public bool TryUpgrade(object @event, out object upgradedEvent);
    public override string ToString(); // e.g. "Orders.ItemAdded@v2"
}
Parameter Description
name The event name in the store.
version The version number, appended as @v{n}. Defaults to 1.
eventUpgrader A type implementing IUpgradeEvent<TOld, TNew> for schema evolution.
namespace Optional prefix, separated by a dot.

IUpgradeEvent<TOldVersion, TNewVersion>

Upgrades an old version of an event to the current version.

public interface IUpgradeEvent<in TOldVersion, out TNewVersion> {
    TNewVersion Upgrade(TOldVersion @event);
}

IRepository<TState, TEvent>

Loads an aggregate from the event store. Registered by the storage integration.

public interface IRepository<TState, TEvent>
    where TState : IState<TState, TEvent> {

    ValueTask<EntityRoot<TState, TEvent>> LoadAsync(
        AggregateIdentifier identifier,
        CancellationToken cancellationToken = default);
}

Throws AggregateRootNotFoundException when no events exist for the given identifier.


AggregatesOptions

Configuration passed to AddAggregates.

public sealed class AggregatesOptions {
    public AggregatesOptions ScanAssemblies(params Assembly[] assemblies);
}

ScanAssemblies discovers all ICommand<TState, TEvent> implementations and registers a CommandHandler for each.


AddAggregates (extension method)

IServiceCollection.AddAggregates(Action<AggregatesOptions>? configure = null) → IAggregatesBuilder

Registers the full command handler decorator chain. Returns a builder for attaching a storage integration.


Aggregates.Sagas

ISaga<TSagaState, TEvent>

Implements the reaction logic for a saga.

public interface ISaga<in TSagaState, in TEvent>
    where TSagaState : IState<TSagaState, TEvent> {

    IAsyncEnumerable<ICommand> ReactAsync(
        TSagaState state,
        TEvent @event,
        CancellationToken cancellationToken = default);
}
Parameter Description
state The saga state after applying the incoming event.
event The triggering event.

SagaContractAttribute

Assigns a stable identity to a saga for checkpointing and versioning.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class SagaContractAttribute(
    string name,
    int version = 1,
    string? @namespace = null,
    string? continueFrom = null,
    bool startFromEnd = false) : Attribute {

    public string? ContinueFrom { get; }
    public bool StartFromEnd { get; }
    public override string ToString(); // e.g. "Orders.OrderFulfillment@v2"
}
Parameter Description
name The saga name.
version The version number. Defaults to 1.
namespace Optional prefix.
continueFrom The fully qualified name of the saga version to continue from. Defaults to the previous version when version > 1.
startFromEnd When true, starts from the current end of the stream on first run — skips historical events.

ISagaIdResolver<TEvent>

Determines which saga instance(s) should handle an incoming event.

public interface ISagaIdResolver<in TEvent> {
    IEnumerable<AggregateIdentifier> Resolve(TEvent @event);
}

SagasOptions

Configuration passed to AddSagas.

public sealed class SagasOptions {
    public SagasOptions ScanAssemblies(params Assembly[] assemblies);
    public SagasOptions WithResolver<TEvent>(ISagaIdResolver<TEvent> resolver);
    public SagasOptions WithResolver<TEvent>(Func<TEvent, IEnumerable<AggregateIdentifier>> resolve);
}
Method Description
ScanAssemblies Discovers all ISaga<TSagaState, TEvent> implementations in the given assemblies.
WithResolver<TEvent> Registers the resolver used to route an event to saga instance(s). Only sagas with a resolver are triggered.

Aggregates.Policies

IPolicy<TEvent>

Implements the reaction logic for a stateless policy.

public interface IPolicy<in TEvent> {
    IAsyncEnumerable<ICommand> ReactAsync(TEvent @event, CancellationToken cancellationToken = default);
}

PolicyContractAttribute

Assigns a stable identity to a policy for checkpointing and versioning.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class PolicyContractAttribute(
    string name,
    int version = 1,
    string? @namespace = null,
    bool startFromEnd = false) : Attribute {

    public bool StartFromEnd { get; }
    public override string ToString(); // e.g. "Users.SendWelcomeEmail@v1"
}
Parameter Description
name The policy name.
version The version number. Defaults to 1.
namespace Optional prefix.
startFromEnd When true, starts from the current end of the stream on first run.

Aggregates.Projections

IProjection<TEvent>

Implements the projection logic for an event type.

public interface IProjection<in TEvent> {
    ValueTask<ICommit> ProjectAsync(TEvent @event, CancellationToken cancellationToken = default);
}

Use a marker interface for TEvent to handle multiple related event types in a single projection while guaranteeing processing order.


ICommit

A composable unit of pending write work.

public interface ICommit {
    ICommit Use(Func<ICommit> applicator);
    ICommit Use<TCommit>(Func<CancellationToken, ValueTask<TCommit>> asyncApplicator)
        where TCommit : ICommit;
    ValueTask CommitAsync(CancellationToken cancellationToken = default);
}
Method Description
Use(Func<ICommit>) Appends a synchronously produced commit to the chain.
Use<TCommit>(Func<ct, ValueTask<TCommit>>) Appends an asynchronously produced commit; deferred until CommitAsync.
CommitAsync Executes all pending work in the chain in order.

Commit

The default ICommit implementation. Use Commit.Create() to start a new chain.

public sealed class Commit : ICommit {
    public static ICommit Create();
}

ProjectionContractAttribute

Assigns a stable identity to a projection for checkpointing and versioning.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class ProjectionContractAttribute(
    string name,
    int version = 1,
    string? @namespace = null,
    bool startFromEnd = false) : Attribute {

    public bool StartFromEnd { get; }
    public override string ToString(); // e.g. "ReadModels.Orders@v1"
}

Aggregates.Subscriptions

ISubscriptionFactory

Creates subscriptions to the event stream. Implemented by storage integration packages.

public interface ISubscriptionFactory {
    ISubscription Subscribe(
        ulong? fromPosition,
        bool startFromEnd,
        CancellationToken cancellationToken = default);
}
Parameter Description
fromPosition Exclusive starting position. null means start from the beginning (unless startFromEnd overrides).
startFromEnd When true and fromPosition is null, starts from the current end of the stream.

ISubscription

An active subscription. Yields SubscriptionMessage values in chronological order.

public interface ISubscription : IAsyncEnumerable<SubscriptionMessage>, IAsyncDisposable { }

SubscriptionMessage

A deserialized event delivered by a subscription.

public readonly record struct SubscriptionMessage(object? Event, ulong CommitPosition);
Member Description
Event The deserialized domain event, or null when the event type is unknown (skipped by handlers).
CommitPosition The global position of this event in the underlying stream. Stored as the new checkpoint.

ICheckpointStore

Persists and retrieves subscription positions. Implemented by storage integration packages.

public interface ICheckpointStore {
    ValueTask<ulong?> GetAsync(string subscriptionId, CancellationToken cancellationToken = default);
    ValueTask StoreAsync(string subscriptionId, ulong position, CancellationToken cancellationToken = default);
}

Clone this wiki locally