Table of Contents

Class EventSourcedRepository<TAggregate, TKey>

Namespace
Excalibur.EventSourcing.Implementation
Assembly
Excalibur.EventSourcing.dll

Event-sourced repository implementation with generic key support, optional automatic event upcasting, and outbox integration.

[SuppressMessage("Maintainability", "CA1506:Avoid excessive class coupling", Justification = "Coordination role; see the note above. Splitting this class is tracked separately.")]
public class EventSourcedRepository<TAggregate, TKey> : IEventSourcedRepository<TAggregate, TKey> where TAggregate : class, IAggregateRoot<TKey>, IAggregateSnapshotSupport where TKey : notnull

Type Parameters

TAggregate

The aggregate type.

TKey

The type of the aggregate identifier.

Inheritance
EventSourcedRepository<TAggregate, TKey>
Implements
IEventSourcedRepository<TAggregate, TKey>
Derived
Inherited Members

Remarks

This repository provides full event sourcing capabilities with strongly-typed keys:

  • Event loading and replay with version tracking
  • Automatic upcasting via IUpcastingPipeline when configured
  • Snapshot support via ISnapshotManager
  • ETag-based optimistic concurrency control
  • Outbox integration for reliable messaging of IIntegrationEvent instances
  • CQRS write-side only — query operations belong in a separate read model

Usage:

services.AddMessageUpcasting(builder => builder
.RegisterUpcaster<OrderCreatedV1, OrderCreatedV2>(new OrderCreatedV1ToV2())
.EnableAutoUpcastOnReplay());

services.AddExcalibur(x => x.AddEventSourcing(builder => builder .AddRepository<OrderAggregate, Guid>()));

Constructors

EventSourcedRepository(IEventStore, IEventSerializer, Func<TKey, TAggregate>, IOptions<EventSourcedRepositoryOptions>, IOptionsMonitor<AutoSnapshotOptions>?, IUpcastingPipeline?, ISnapshotManager?, ISnapshotStrategy?, ITransactionalOutboxWriter?, IOutboxStore?, SnapshotVersionManager?, IEventNotificationBroker?, TimeProvider?, ILogger<EventSourcedRepository<TAggregate, TKey>>?)

Initializes a new instance of the EventSourcedRepository<TAggregate, TKey> class using the Options pattern for configuration.

public EventSourcedRepository(IEventStore eventStore, IEventSerializer eventSerializer, Func<TKey, TAggregate> aggregateFactory, IOptions<EventSourcedRepositoryOptions> options, IOptionsMonitor<AutoSnapshotOptions>? autoSnapshotOptions = null, IUpcastingPipeline? upcastingPipeline = null, ISnapshotManager? snapshotManager = null, ISnapshotStrategy? snapshotStrategy = null, ITransactionalOutboxWriter? transactionalOutboxWriter = null, IOutboxStore? outboxStore = null, SnapshotVersionManager? snapshotVersionManager = null, IEventNotificationBroker? eventNotificationBroker = null, TimeProvider? timeProvider = null, ILogger<EventSourcedRepository<TAggregate, TKey>>? logger = null)

Parameters

eventStore IEventStore

The event store for persistence.

eventSerializer IEventSerializer

The event serializer for deserialization.

aggregateFactory Func<TKey, TAggregate>

Factory function to create aggregate instances from a key.

options IOptions<EventSourcedRepositoryOptions>

Configuration options for the repository.

autoSnapshotOptions IOptionsMonitor<AutoSnapshotOptions>

Optional auto-snapshot configuration for automatic snapshot creation after save.

upcastingPipeline IUpcastingPipeline

Optional upcasting pipeline for version transformation.

snapshotManager ISnapshotManager

Optional snapshot manager.

snapshotStrategy ISnapshotStrategy

Optional snapshot strategy.

transactionalOutboxWriter ITransactionalOutboxWriter

Optional transactional outbox writer for staging integration events atomically with event appends.

outboxStore IOutboxStore

Optional outbox store for eventually-consistent staging when transactional writer is unavailable.

snapshotVersionManager SnapshotVersionManager

Optional snapshot version manager for automatic snapshot upgrading.

eventNotificationBroker IEventNotificationBroker

Optional broker for the post-commit notification handlers.

timeProvider TimeProvider

Optional time provider for deterministic testing.

logger ILogger<EventSourcedRepository<TAggregate, TKey>>

Optional logger for diagnostics.

Properties

TransactionalProjections

Gets the optional coordinator used for transactionally registered read models.

public ITransactionalProjectionCoordinator? TransactionalProjections { get; init; }

Property Value

ITransactionalProjectionCoordinator

The coordinator supplied by event-sourcing registration, or null.

Methods

DeleteAsync(TAggregate, CancellationToken)

Soft-deletes an aggregate by appending a tombstone event.

public virtual Task DeleteAsync(TAggregate aggregate, CancellationToken cancellationToken)

Parameters

aggregate TAggregate

The aggregate to delete.

cancellationToken CancellationToken

The cancellation token.

Returns

Task

A task that represents the asynchronous delete operation.

Remarks

This performs a soft delete by marking the aggregate as deleted. The aggregate's event history is preserved for audit purposes.

ExistsAsync(TKey, CancellationToken)

Checks if an aggregate exists.

public Task<bool> ExistsAsync(TKey aggregateId, CancellationToken cancellationToken)

Parameters

aggregateId TKey

The aggregate identifier.

cancellationToken CancellationToken

The cancellation token.

Returns

Task<bool>

true if the aggregate exists; otherwise, false.

GetByIdAsync(TKey, CancellationToken)

Gets an aggregate by its strongly-typed identifier.

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Optional snapshot upgrading and serialization use reflection; the repository's own rehydration is a delegate-factory + pattern-matched apply (no reflection). AOT consumers select an AOT-safe serializer and the interface contract stays clean.")]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "Optional snapshot upgrading and serialization may use dynamic code; the repository's own rehydration does not.")]
public Task<TAggregate?> GetByIdAsync(TKey aggregateId, CancellationToken cancellationToken)

Parameters

aggregateId TKey

The aggregate identifier.

cancellationToken CancellationToken

The cancellation token.

Returns

Task<TAggregate>

The aggregate if found; null if no stream exists for the identifier; or an aggregate in its initial state -- Version 0, no history applied -- if the stream exists but has been erased. The erased case is deliberately distinct from both: it is not null, because the subject did exist, and it does not throw, because the erasure was lawful rather than a corruption. A caller that only null-checks will treat an erased stream as a live aggregate that happens to have no history.

SaveAsync(TAggregate, string?, CancellationToken)

Saves an aggregate with ETag-based optimistic concurrency check.

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Optional serialization uses reflection; the repository's own persistence path does not. AOT consumers select an AOT-safe serializer and the interface contract stays clean.")]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "Optional serialization may use dynamic code; the repository's own persistence path does not.")]
public Task<SaveResult> SaveAsync(TAggregate aggregate, string? expectedETag, CancellationToken cancellationToken)

Parameters

aggregate TAggregate

The aggregate to save.

expectedETag string

The expected ETag value. If the current ETag doesn't match, a ConcurrencyException is thrown. Pass null to skip ETag validation.

cancellationToken CancellationToken

The cancellation token.

Returns

Task<SaveResult>

A task that represents the asynchronous save operation.

Exceptions

ConcurrencyException

Thrown when the expected ETag doesn't match the current aggregate ETag.

SaveAsync(TAggregate, CancellationToken)

Saves an aggregate and its uncommitted events.

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode", Justification = "Optional serialization uses reflection; the repository's own persistence path does not. AOT consumers select an AOT-safe serializer and the interface contract stays clean.")]
[UnconditionalSuppressMessage("AOT", "IL3050:RequiresDynamicCode", Justification = "Optional serialization may use dynamic code; the repository's own persistence path does not.")]
[SuppressMessage("Maintainability", "CA1506:Avoid excessive class coupling", Justification = "SaveAsync orchestrates event append, transactional outbox, fallback outbox, snapshots, and notifications -- coupling is inherent to the coordination role.")]
public Task<SaveResult> SaveAsync(TAggregate aggregate, CancellationToken cancellationToken)

Parameters

aggregate TAggregate

The aggregate to save.

cancellationToken CancellationToken

The cancellation token.

Returns

Task<SaveResult>

A task that represents the asynchronous save operation.