Skip to content

API Reference

Wouter Naessens edited this page Oct 7, 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>(TState? state, AggregateVersion version)
    : 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.

EventTypeRegistry

A bidirectional mapping between CLR event types and the type names used to store them. Build one instance at startup by scanning your event assemblies, then use it inside the Serialize and Deserialize delegates on the storage integration options.

For each type decorated with [EventContract], the stored name is taken from EventContractAttribute.ToString() (e.g. Orders.ItemAdded@v2). Types without the attribute fall back to their short CLR type name.

Register all event type versions — current and historical — in the same registry so that old events stored under an earlier type name can still be looked up and deserialized.

public sealed class EventTypeRegistry {
    public static EventTypeRegistry FromAssemblies(params Assembly[] assemblies);
    public string GetTypeName(Type type);
    public string GetTypeName<TEvent>(TEvent @event);
    public bool TryGetType(string typeName, out Type type);
}
Method Description
FromAssemblies(assemblies) Scans the given assemblies for non-abstract types decorated with [EventContract] and builds the registry.
GetTypeName(type) Returns the stored type name for a CLR type. Falls back to type.Name when no [EventContract] is present.
GetTypeName<TEvent>(event) Convenience overload — equivalent to GetTypeName(@event.GetType()). Uses the runtime type, so it works correctly when the declared type is a base class or interface.
TryGetType(typeName, out type) Looks up the CLR type for a stored type name. Returns false when the name is unknown (e.g. a removed event or an event from another service).
var registry = EventTypeRegistry.FromAssemblies(typeof(OrderPlaced).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;
});

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.


MetadataScope

An ambient, async-local scope that accumulates metadata entries for the event(s) written during a single command execution. Opened automatically by MetadataAwareCommandHandler; you can also write to it directly via MetadataScope.Current?.Add(...).

public sealed class MetadataScope : IAsyncDisposable {
    public MetadataScope();
    public MetadataScope(EventMetadata seed);

    public static MetadataScope? Current { get; }

    public void Add(string key, object? value,
        MetadataMultiplicity multiplicity = MetadataMultiplicity.Single);

    public EventMetadata Snapshot();
}
Member Description
MetadataScope() Opens a new empty scope and pushes it onto the ambient stack.
MetadataScope(seed) Opens a new scope pre-populated from seed and pushes it onto the stack. Array values in the seed are restored as accumulators so further Multiple additions append correctly.
Current The innermost active scope, or null when no scope is active.
Add Adds or updates an entry. Single overwrites; Multiple appends (duplicates are ignored).
Snapshot Materialises the current entries as an immutable EventMetadata. Multiple entries are converted to arrays.

Scopes nest: creating a new scope pushes it; disposing pops it. The expected usage is await using var scope = new MetadataScope(...).


MetadataMultiplicity

Controls how repeated writes to the same key are handled.

public enum MetadataMultiplicity {
    Single,   // overwrite — only the last value is kept
    Multiple  // accumulate — all distinct values are kept as an array
}

EventMetadata

An immutable snapshot of a MetadataScope. Implements IReadOnlyDictionary<string, object?>. Multiple entries appear as object?[].

public sealed class EventMetadata : IReadOnlyDictionary<string, object?> {
    public static EventMetadata Empty { get; }
}

MetadataAttribute

Apply to a state or command class to automatically populate the ambient MetadataScope whenever an instance of that type is processed by EntityRoot.AcceptAsync.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct,
    AllowMultiple = true, Inherited = true)]
public abstract class MetadataAttribute(
    string key,
    MetadataMultiplicity multiplicity = MetadataMultiplicity.Single) : Attribute {

    public string Key { get; }
    public MetadataMultiplicity Multiplicity { get; }

    public abstract ValueTask<object?> GetValueAsync(
        object context, CancellationToken cancellationToken);
}

Subclass this and override GetValueAsync. The context parameter is the decorated object (state or command); cast it to the expected type in your implementation.

// Example: stamp a correlation identifier from the command onto every event.
sealed class CorrelationIdAttribute() : MetadataAttribute("correlationId") {
    public override ValueTask<object?> GetValueAsync(object context, CancellationToken ct) =>
        ValueTask.FromResult<object?>(((MyCommand)context).CorrelationId);
}

[CorrelationId]
record MyCommand(AggregateIdentifier Id, string CorrelationId, ...) : ICommand<...> { ... }

AggregatesOptions

Configuration passed to AddAggregates.

public sealed class AggregatesOptions {
    public AggregatesOptions ScanAssemblies(params Assembly[] assemblies);
    public AggregatesOptions ScanTypes(params Type[] types);
}
Method Description
ScanAssemblies Discovers all ICommand<TState, TEvent> implementations in the given assemblies and registers a CommandHandler for each.
ScanTypes Same, but only for the given types. Use it to register an explicit set of commands instead of everything in an assembly.

Both can be combined; a type found by both is registered once.


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, EventMetadata metadata);
}

The metadata parameter carries the stored metadata of the incoming event. This is the primary way to resolve saga identifiers when they are written to metadata at the time the triggering event is produced — a common pattern when multiple saga types can be identified from the same event stream without embedding saga-specific identifiers in the event body itself.

Registering a resolver for a base event interface covers all its subtypes through a single registration, keeping the DI setup compact:

// One registration handles all IOrderEvent subtypes.
.WithResolver<IOrderEvent>((_, metadata) =>
    metadata.TryGetValue("SagaId", out var value) && value is object?[] ids
        ? ids.OfType<string>().Select(id => new AggregateIdentifier(id))
        : [])

When the saga ID is a property on the event body rather than metadata, use the single-parameter overload (see SagasOptions below).


SagasOptions

Configuration passed to AddSagas.

public sealed class SagasOptions {
    public SagasOptions ScanAssemblies(params Assembly[] assemblies);
    public SagasOptions ScanTypes(params Type[] types);
    public SagasOptions WithResolver<TEvent>(ISagaIdResolver<TEvent> resolver);
    public SagasOptions WithResolver<TEvent>(Func<TEvent, EventMetadata, IEnumerable<AggregateIdentifier>> resolve);
    public SagasOptions WithResolver<TEvent>(Func<TEvent, IEnumerable<AggregateIdentifier>> resolve);
}
Method Description
ScanAssemblies Discovers all ISaga<TSagaState, TEvent> implementations in the given assemblies.
ScanTypes Same, but only for the given types.
WithResolver<TEvent>(event, metadata) Registers a resolver receiving both event and metadata. Use when saga identifiers are stored in metadata.
WithResolver<TEvent>(event) Registers a resolver receiving the event only. Use when the saga identifier is a property on the event body.

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.

PoliciesOptions

Configuration passed to AddPolicies.

public sealed class PoliciesOptions {
    public PoliciesOptions ScanAssemblies(params Assembly[] assemblies);
    public PoliciesOptions ScanTypes(params Type[] types);
}
Method Description
ScanAssemblies Discovers all IPolicy<TEvent> implementations in the given assemblies and registers a subscription for each.
ScanTypes Same, but only for the given types.

Aggregates.Projections

IProjection<TEvent>

Implements the projection logic for an event type.

public interface IProjection<in TEvent> {
    ValueTask<ICommit> ProjectAsync(TEvent @event, EventMetadata metadata, 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"
}

ProjectionsOptions

Configuration passed to AddProjections.

public sealed class ProjectionsOptions {
    public ProjectionsOptions ScanAssemblies(params Assembly[] assemblies);
    public ProjectionsOptions ScanTypes(params Type[] types);
}
Method Description
ScanAssemblies Discovers all IProjection<TEvent> implementations in the given assemblies and registers a subscription for each.
ScanTypes Same, but only for the given types.

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,
    EventMetadata Metadata);
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.
Metadata The metadata stored alongside the event, or EventMetadata.Empty when none is present or the integration does not provide a DeserializeMetadata delegate.

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);
}

IParkedMessageSink

Receives messages that could not be processed after all retry attempts have been exhausted.

public interface IParkedMessageSink {
    ValueTask ParkAsync(
        string subscriptionId,
        SubscriptionMessage message,
        Exception exception,
        CancellationToken cancellationToken = default);
}
Parameter Description
subscriptionId The subscription that owns the failed message.
message The message that could not be processed.
exception The exception from the final failed attempt.

The default implementation (LoggingParkedMessageSink) logs a warning and returns without persisting. Storage integration packages register a persistent implementation that appends a ParkedMessage event to a parked-{subscriptionId} stream. Register your own implementation as a singleton to override either default:

services.AddSingleton<IParkedMessageSink, MyCustomParkedMessageSink>();

SubscriptionErrorHandlingOptions

Controls retry behaviour for all subscription hosted services.

public sealed class SubscriptionErrorHandlingOptions {
    public int MaxRetries { get; set; } = 5;
    public TimeSpan InitialDelay { get; set; } = TimeSpan.FromSeconds(1);
    public TimeSpan MaxDelay { get; set; } = TimeSpan.FromSeconds(30);
    public double BackoffMultiplier { get; set; } = 2.0;
}
Property Default Description
MaxRetries 5 Total number of attempts per message (including the first).
InitialDelay 1 s Delay before the second attempt.
MaxDelay 30 s Upper bound on the delay between attempts.
BackoffMultiplier 2.0 Factor by which the delay grows after each failed attempt.

Register a custom instance as a singleton before calling AddSagas / AddPolicies / AddProjections to override all defaults at once.

Clone this wiki locally