Xpandables.Events
11.0.0
dotnet add package Xpandables.Events --version 11.0.0
NuGet\Install-Package Xpandables.Events -Version 11.0.0
<PackageReference Include="Xpandables.Events" Version="11.0.0" />
<PackageVersion Include="Xpandables.Events" Version="11.0.0" />
<PackageReference Include="Xpandables.Events" />
paket add Xpandables.Events --version 11.0.0
#r "nuget: Xpandables.Events, 11.0.0"
#:package Xpandables.Events@11.0.0
#addin nuget:?package=Xpandables.Events&version=11.0.0
#tool nuget:?package=Xpandables.Events&version=11.0.0
π¦ System.Events
Event-driven architecture framework with in-process pub/sub, domain event sourcing, outbox/inbox pattern, and aggregate persistence
Getting Started β’ Events β’ Event Bus β’ Event Sourcing β’ Aggregates β’ Correlation β’ Outbox/Inbox β’ Scheduler β’ Storage β’ DI Registration β’ Native AOT
π Overview
Xpandables.Events provides a complete event-driven architecture for .NET 11 applications:
- in-process publish-subscribe messaging, with DI consumers and delegate subscribers;
- domain event sourcing with full stream management (append with optimistic concurrency, read, read all, polling subscriptions, soft/hard delete, truncate, snapshots);
- aggregates with event handlers, business versioning, snapshots (memento) and an optional state machine, persisted atomically with their integration events;
- a transactional outbox and an idempotent inbox for integration events, with leases, fenced claims, retries and parking;
- a background scheduler that delivers the outbox in parallel, the events of one partition key in order, with a circuit breaker, backoff and a health check;
- ADO.NET stores over Xpandables.Data, and SQL DDL scripts for SQL Server, PostgreSQL and SQLite.
Everything is Native AOT compatible: consumers, event names and data records are generated at compile time.
π Getting Started
dotnet add package Xpandables.Events
Xpandables.Events depends on Xpandables.Net and Xpandables.Data, and brings Xpandables.Generators: the consumer registrations, the event-name registry and the data records of the stores are generated at compile time (see Native AOT).
A complete registration, for an application assembly named MyApp on PostgreSQL:
using System.Data.Common;
using System.Events.Generated; // AddXMyAppEventConsumers (generated)
using System.Text.Json;
using System.Text.Json.Serialization;
using Microsoft.Extensions.DependencyInjection;
using Npgsql;
// Database (Xpandables.Data): the stores write through its IDataUnitOfWork. UsePostgreSql takes its connections
// from the provider registered in DbProviderFactories.
DbProviderFactories.RegisterFactory("Npgsql", NpgsqlFactory.Instance);
builder.Services.AddXData(data => data.UsePostgreSql(connectionString));
// Serialization (Xpandables.Net): every event and memento type must be in the JSON context.
builder.Services.AddSingleton<IJsonSerializerContext>(new DefaultJsonSerializerContext(
new JsonSerializerOptions { TypeInfoResolver = OrdersJsonContext.Default }));
// Event names (generated): the stores read events back by their persisted name.
builder.Services.AddXShopApiCacheTypes(); // and AddXShopOrdersCacheTypes() of each project that declares events
builder.Services
.AddXEventContextAccessor() // correlation/causation context
.AddXDomainEventEnricher() // used by the aggregate store
.AddXIntegrationEventEnricher() // used by the outbox store
.AddXEventPublisher() // in-process publisher, subscriber and consumer registry (singleton)
.AddXMyAppEventConsumers() // every IEventConsumer<T> of the assembly (generated)
.AddXEventConverterProvider()
.AddXEventConverters() // domain, snapshot, outbox and inbox converters
.AddXAllEventStores() // IEventStore, IOutboxStore, IInboxStore
.AddXPendingIntegrationEvents()
.AddXAggregateStore<OrderAggregate>()
.AddXScheduler() // the outbox scheduler
.AddXHostedScheduler() // runs it as a background service
.AddXSchedulerHealthCheck();
[JsonSerializable(typeof(OrderCreatedEvent))]
[JsonSerializable(typeof(ItemAddedEvent))]
[JsonSerializable(typeof(OrderSubmittedIntegrationEvent))]
[JsonSerializable(typeof(OrderMemento))]
internal sealed partial class OrdersJsonContext : JsonSerializerContext;
Create the tables with the built-in scripts before the first use.
π§Ύ Events
Every event implements IEvent: EventId (a version 7 GUID by default), OccurredOn (UTC now by default),
CausationId and CorrelationId (strings; for HTTP flows the correlation header value (X-Correlation-Id by
default), else the trace id of the request's W3C activity, else a new identifier - never the traceparent trace
context), and TryGetCausationGuidId/TryGetCorrelationGuidId to parse those ids as GUIDs.
| Base type | Namespace | Use |
|---|---|---|
EventBase |
System.Events |
Any in-process event |
DomainEvent |
System.Events.DomainEvents |
An event of an event-sourced stream: StreamId (required), StreamName, StreamVersion, Metadata |
IntegrationEvent |
System.Events.IntegrationEvents |
An event crossing service boundaries (outbox, inbox, bus) |
IntegrationEvent<TDomainEvent> |
System.Events.IntegrationEvents |
An integration event carrying the domain event it was raised for (DomainEvent) |
SnapshotEvent |
System.Events.DomainEvents |
A snapshot of an aggregate (written by the aggregate store) |
DomainEvent and IntegrationEvent are immutable records changed through With⦠methods that return a copy:
WithStreamId, WithStreamVersion, WithStreamName, WithCausation, WithCorrelation and WithMetadata on
IDomainEvent; WithCausation and WithCorrelation on IIntegrationEvent. Domain event Metadata holds JSON
primitives only (string, int, long, float, double, decimal, bool, null); any other value throws
JsonException when it is written, and numbers are read back as long (integers) or double.
Event names and versions
An event is persisted under its [EventName] value, else its simple type name, and at its Version (1 by default).
The name is a wire contract: renaming or moving the class must not change it, so declare it on every persisted event.
A renamed event keeps its former names in [EventNameAlias] (repeatable): rows stored under them are read back as it.
[EventName("Ordering.OrderCreated", Version = 2)]
[EventNameAlias("Ordering.OrderCreated.v1")]
public sealed record OrderCreatedEvent : DomainEvent
{
public required string OrderNumber { get; init; }
public decimal Amount { get; init; }
}
Names, versions and aliases are read at compile time into the EventTypeRegistry, to which the generated
AddX{Assembly}CacheTypes() of each project adds its own events, internal ones included; nothing reads them at run
time, and an event type the registry does not list cannot be stored (InvalidOperationException). A row whose name
is neither a name nor an alias throws UnknownEventTypeException (EventName). Two event types sharing a name
fail the build (XCT001), as do an alias that
repeats the name or an alias of another event (XCT003), an empty name or alias (XCT002) and a version below 1
(XCT004).
Event versions and upcasting
Every row stores the version its payload was written at (EventVersion). A row stored at an older version is upcast
before it is deserialized: the IEventUpcasters of the event (registered under its current name, never an alias) run
from the stored version to the type's, each turning version FromVersion into FromVersion + 1. A missing step throws
EventUpcastException (EventName, FromVersion, ToVersion), as does a row stored at a version above the type's.
public sealed class OrderCreatedFromVersionOne : IEventUpcaster
{
public string EventName => "Ordering.OrderCreated";
public int FromVersion => 1;
// Version 1 called the amount "Total".
public void Upcast(ref Utf8JsonReader source, Utf8JsonWriter target)
{
JsonObject payload = JsonNode.Parse(ref source)!.AsObject();
if (payload.Remove("Total", out JsonNode? total))
{
payload["Amount"] = total;
}
payload.WriteTo(target);
}
}
services.AddXEventUpcaster<OrderCreatedFromVersionOne>();
EventSerializer (registered by AddXEventConverters()) is the component that writes and reads the payloads: the
stores use it, and an adapter reading events from a broker does too (Deserialize(name, version, utf8Payload)).
Event status
EventStatus holds the states the stores persist, by name: ACTIVE and DELETED (stream events), PENDING,
PROCESSING, ONERROR and PROCESSED (outbox and inbox rows), SUSPENDED (inbox), and the receive results
ACCEPTED and DUPLICATE.
π‘ Event Bus (Pub/Sub)
using System.Events;
public sealed record OrderSubmittedEvent : EventBase
{
public required Guid OrderId { get; init; }
public required decimal Amount { get; init; }
}
// Publish (IEventPublisher is registered by AddXEventPublisher(); here built by hand)
IEventPublisher publisher = new EventPublisherSubscriber(registry);
await publisher.PublishAsync(new OrderSubmittedEvent { OrderId = Guid.NewGuid(), Amount = 99.95m });
// Several events, one after another
await publisher.PublishAsync([firstEvent, secondEvent], ct);
// Subscribe a delegate (sync or async) or a consumer instance
IEventSubscriber subscriber = (IEventSubscriber)publisher;
subscriber.Subscribe<OrderSubmittedEvent>(evt => Console.WriteLine($"Order {evt.OrderId} submitted"));
subscriber.Subscribe<OrderSubmittedEvent>(async (evt, token) => await audit.WriteAsync(evt, token));
Action<OrderSubmittedEvent> handler = evt => metrics.Count(evt);
subscriber.Subscribe(handler);
subscriber.Unsubscribe(handler); // false when it was not subscribed
using IDisposable subscription = subscriber.SubscribeDisposable<OrderSubmittedEvent>(evt => { }); // disposing unsubscribes
EventPublisherSubscriber is both the publisher and the subscriber; AddXEventPublisher() registers one instance
(singleton by default) as EventPublisherSubscriber, IEventSubscriber and, when no IEventPublisher is registered
yet, IEventPublisher. A publish reaches:
- the delegate subscribers of the event's runtime type, of its base types and of its interfaces; the same handler subscribed twice is kept once;
- the DI consumers (
IEventConsumer<T>) of the event's own type first, then of its base types (most derived first), then of its interfaces, one after another.
Synchronous delegates run one after another on the publishing thread; asynchronous delegates and the chain of DI
consumers then run concurrently. A delegate that throws does not stop the
other delegates nor the DI consumers; a DI consumer that throws stops the DI consumers after it. The publish then
throws the failure (the handler's own exception, not wrapped). Publishing an event nobody handles does nothing.
Subscriptions are thread-safe; publishing reads a snapshot of them cached per event type.
The PublishAsync(IEnumerable<IEvent>) extension publishes in order and stops at the first failure, which propagates
as it is (a cancellation stays an OperationCanceledException). The token is checked before each event.
Event consumers
public sealed class OrderSubmittedHandler(IEmailService emailService) : IEventConsumer<OrderSubmittedEvent>
{
public async Task ConsumeAsync(OrderSubmittedEvent @event, CancellationToken cancellationToken) =>
await emailService.SendOrderConfirmationAsync(@event.OrderId, cancellationToken);
}
// Register every consumer of the assembly (generated for the assembly "MyApp", in System.Events.Generated)
services.AddXMyAppEventConsumers();
// ... or one consumer by hand
services.AddXEventConsumer<OrderSubmittedEvent, OrderSubmittedHandler>(factory: null);
services.AddXEventConsumer<OrderSubmittedEvent, OrderSubmittedHandler>(
sp => new OrderSubmittedHandler(sp.GetRequiredService<IEmailService>()));
Consumers are transient. A consumer type is registered once per event, so that it runs once: a registration without a factory adds nothing when the consumer is already registered, and one with a factory replaces the consumer's other registration (generated or not, in any order). A factory typed as an abstract class or an interface is always added. A consumer of an integration event is registered through the inbox (see Integration event consumers), and must then be a concrete type.
Consumers are resolved from the ambient request scope when there is one. Without it (a background service, a broker callback), the consumers of one publish get a new scope, shared by the consumers of the event's type, base types and interfaces, and disposed after the publish.
Registry modes
AddXEventPublisher(EventRegistryMode registryMode = Default) chooses where DI consumers come from (the publisher is a
singleton: one instance holds the subscriptions publishing reads). The registry is resolved by the mode recorded, so
AddXEventSubscriber() and AddXIntegrationEventReceiver() work alone (static registry) and in any order with it:
| Mode | Registry | Consumers |
|---|---|---|
Default, Static |
StaticEventConsumerRegistry |
The registered IEventConsumerWrappers, fixed at startup |
Dynamic |
DynamicEventConsumerRegistry |
Consumer instances registered at run time |
Composite |
CompositeEventConsumerRegistry |
Both; for one event type the dynamic registration wins |
services.AddXEventPublisher(EventRegistryMode.Composite);
var dynamicRegistry = app.Services.GetRequiredService<DynamicEventConsumerRegistry>();
dynamicRegistry.Register<PluginEvent>([new PluginEventHandler()]); // replaces earlier ones for PluginEvent
dynamicRegistry.Unregister<PluginEvent>(); // false when none was registered
External bus
public sealed class RabbitBus : IEventBus
{
public Task PublishAsync(IntegrationEventEnvelope envelope, CancellationToken cancellationToken = default) => ...;
}
services.AddXEventPublisher(); // in-process consumers: domain events, notifications
services.AddXEventBus<RabbitBus>(); // the outbox relay publishes the integration events to the bus
IEventPublisher publishes in process: domain events, notifications, and an integration event you publish yourself.
Integration events reach other processes through the outbox: the relay delivers each claimed event to exactly one
target, the registered IEventBus when there is one, else the in-process IIntegrationEventReceiver.
AddXEventBus<T>() registers the bus (replacing an earlier one) for the relay only: it is not an IEventPublisher.
IntegrationEventEnvelope is the wire contract of a bus adapter: the event's id, name and version, its partition key
(map it to the broker's ordering key), its correlation and causation ids, the W3C trace context, the UTF-8 JSON payload
and the time it was written to the outbox. The consuming process hands each message it receives to the receiver
(AddXIntegrationEventReceiver()):
try
{
await receiver.ReceiveAsync(envelope, ct);
await message.AckAsync();
}
catch (InboxEventDeferredException deferred)
{
await message.NackAsync(requeue: true); // not processed now: redeliver after deferred.RetryAfter when known
}
The receiver resolves the event by its name and version (the upcasters of an older version run first), then runs every
consumer of its type, base types and interfaces in one scope (the ambient request scope, else one of its own), each one
even when another failed. Every consumer of an integration event (registered with AddXIntegrationEventConsumer,
AddXEventConsumer or the generated registration) runs through the inbox, so a redelivered event runs only the
consumers that have not completed it. One failure is rethrown as it is; several are an AggregateException; when every
consumer that did not complete deferred the event, the deferral with the latest RetryAfter is thrown.
π Event Sourcing
using System.Events.DomainEvents;
// The store is registered by AddXEventStore() (or AddXAllEventStores()) over Xpandables.Data.
IEventStore store = scope.ServiceProvider.GetRequiredService<IEventStore>();
// Append: ExpectedVersion is the stream's current version (-1 for a new stream);
// null appends after whatever the stream holds, without a check.
AppendResult result = await store.AppendToStreamAsync(new AppendRequest
{
StreamId = streamId,
Events = [new OrderCreatedEvent { StreamId = streamId, OrderNumber = "ORD-1" }],
ExpectedVersion = -1,
}, ct);
// result.FirstAssignedStreamVersion == 0, result.LastAssignedStreamVersion == 0, result.EventIds
// Read a stream: FromVersion is inclusive (0 reads from the first event); MaxCount 0 or less, or int.MaxValue, reads all
await foreach (EnvelopeResult envelope in store.ReadStreamAsync(
new ReadStreamRequest { StreamId = streamId, FromVersion = 0, MaxCount = 100 }, ct))
{
ProcessEvent(envelope.Event);
}
// Read every stream in commit order, after a position (EventPosition.Start, the default, reads from the first event);
// MaxCount 0 means no limit. Continue from the last envelope's Position.
await foreach (EnvelopeResult envelope in store.ReadAllStreamsAsync(
new ReadAllStreamsRequest { After = EventPosition.Start, MaxCount = 0 }, ct)) { }
long version = await store.GetStreamVersionAsync(streamId, ct); // -1 when the stream does not exist
bool exists = await store.StreamExistsAsync(streamId, ct);
// Subscribe (polling): the callback receives each event from FromVersion on, then each new one
await using IAsyncDisposable subscription = store.SubscribeToStream(new SubscribeToStreamRequest
{
StreamId = streamId,
FromVersion = 0,
PollingInterval = TimeSpan.FromSeconds(1), // the default
OnEvent = @event => { ProcessEvent(@event); return ValueTask.CompletedTask; },
}, ct);
// Delete, in one transaction (the store's own when none is active). A soft delete appends a tombstone at the next
// version (a concurrent append makes one of them fail) and hides the stream: its id stays taken (appending throws
// EventStreamDeletedException). A hard delete removes its events and its snapshots, and frees the id.
// ExpectedVersion (optional, -1 for a soft-deleted stream) is enforced by both: at an expected version, a hard delete
// claims the next version first, as a soft delete does.
await store.DeleteStreamAsync(new DeleteStreamRequest { StreamId = streamId, HardDelete = false, ExpectedVersion = version }, ct);
// Truncate: removes the events before a version, for good β never past the latest snapshot (clamped to its version + 1)
// nor the last event; a stream without a restorable snapshot (StreamVersion >= 0, BusinessVersion >= 1) is refused,
// and TruncateBeforeVersion 0 or less does nothing
await store.TruncateStreamAsync(new TruncateStreamRequest { StreamId = streamId, TruncateBeforeVersion = 100 }, ct);
An EnvelopeResult carries the event and its EventId, EventName, GlobalPosition (the row's sequence: insertion
order, not commit order, so resume a global read from Position), Position (a global read's EventPosition),
OccurredOn (when the row was stored, UTC), StreamId, StreamName, StreamVersion, CausationId and
CorrelationId.
Appending. Only domain events can be appended (ArgumentException otherwise). The store stamps each event with the
stream id and the next version. An empty batch appends nothing, but is checked like any append. A soft-deleted stream throws
EventStreamDeletedException (StreamId); a stale ExpectedVersion throws EventStreamConcurrencyException.
Concurrency. An append based on a stale version throws EventStreamConcurrencyException (StreamId,
ExpectedVersion, ActualVersion; it derives from InvalidOperationException) β also when two writers race and the
database's unique (StreamId, StreamVersion) index refuses the loser, under any isolation level. Under a snapshot (SQL
Server SNAPSHOT, PostgreSQL REPEATABLE READ or SERIALIZABLE), or when the database rolled the transaction back, the
winner cannot be read, so ActualVersion is null; so is it on PostgreSQL inside an ambient System.Transactions
transaction, which takes no savepoint: the refused insert ends the transaction, and the transaction scope must be
disposed without completing it. There, any unique violation of the append (a reused EventId, a custom unique column)
and a serialization failure (40001) are reported as the concurrency exception, the provider's error as its
InnerException.
On SQLite, an append refused because another connection holds the write lock (SQLITE_BUSY, SQLITE_LOCKED, after the
connection's busy timeout) throws it too, with ActualVersion null. Reload and retry:
try
{
await aggregateStore.AppendAsync(order, ct);
}
catch (EventStreamConcurrencyException)
{
order = await aggregateStore.ReadAsync(order.StreamId, ct); // then apply the command again
}
Deleting. Inside a caller's transaction, a delete joins it; a delete that fails β a stale ExpectedVersion
included β marks that transaction rollback-only, so the caller's commit then fails too. Two soft deletes without an
ExpectedVersion can race: the stream ends deleted either way, and the one that finds the other's tombstone does
nothing (on PostgreSQL inside an ambient System.Transactions transaction, which cannot be read after the refused
tombstone, it throws EventStreamConcurrencyException). A hard delete at ExpectedVersion = -1 of a missing stream
leaves everything as it is, its leftover snapshots included. An append blocked by a hard delete's claim of the next
version goes on once the delete commits: the stream then restarts at that version, with no events below it, and
reading its aggregate throws EventStreamCorruptedException until it is deleted again. A tombstone (and a hard
delete's claim) is a copy of the head row: a custom record with a unique constraint on another copied column makes both
deletes fail with the database's own exception. A hard delete's events are gone from ReadAllStreamsAsync and every
all-streams subscription too: a subscription behind them, or one rebuilt with StartFrom.Beginning, never receives
them.
Reads. Soft-deleted events and snapshots are invisible to every read, version query and subscription: a
soft-deleted stream reports version -1 and StreamExistsAsync false. A soft delete's tombstone row ($StreamDeleted)
is never returned. ReadStreamRequest.MaxCount and ReadAllStreamsRequest.MaxCount read everything when 0 or less.
Truncating. Truncating a soft-deleted or missing stream, or with TruncateBeforeVersion 0 or less, does nothing;
truncating a stream whose latest snapshot is missing or cannot be restored (StreamVersion below 0 or BusinessVersion
below 1, which the aggregate store replays in full) throws InvalidOperationException. The truncation is one DELETE,
in the active transaction when there is one; the store opens none, and the clamp is read before it: do not truncate a
stream that may be hard-deleted and recreated meanwhile (the DELETE would remove the new stream's first events). A
truncated stream is read back only through its latest snapshot, so keep snapshotting enabled for its aggregate: without
the snapshot, an AggregateStore with snapshots disabled, or a latest snapshot that cannot be restored (an
AppendSnapshotAsync with BusinessVersion 0, for instance), the stream is replayed from its first event and the read
throws EventStreamCorruptedException; when the latest snapshot cannot be read at all it throws
InvalidOperationException, the snapshot's failure as its inner exception. Both derive from
InvalidOperationException. Truncated events are gone from ReadAllStreamsAsync and every all-streams subscription
too: truncate only below the checkpoint of every subscription that needs them; a projection rebuilt from the beginning
sees the truncated part of the stream only through the aggregate's snapshot, never as events.
Global order. ReadAllStreamsAsync and SubscribeToAllStreams return the rows of every stream in commit order,
and only below the database's low-water mark β no transaction that could still commit a lower position is open β so a
reader that continues from the last Position never skips a row that committed late. A position is an
EventPosition: opaque, comparable, written as text by ToString() and read back by EventPosition.Parse. SQL Server
orders by the domain table's CommitToken (rowversion, below MIN_ACTIVE_ROWVERSION()), PostgreSQL by CommitToken
(xid8: the writing transaction, below pg_snapshot_xmin(pg_current_snapshot())) then Sequence, and SQLite (one
writer at a time) by Sequence; the scripts create the column and its index. A transaction left open anywhere holds
back every row written after it began, not only one of the event store: on SQL Server any open transaction that wrote a
rowversion in the database, on PostgreSQL any transaction holding a transaction id in the cluster, prepared
transactions included. On SQL Server a global read refuses to run inside a SNAPSHOT transaction (error 50000): its
snapshot could predate rows committed below the mark, so run it outside a SNAPSHOT transaction. EventPosition
serializes with System.Text.Json as its text (EventPositionJsonConverter). MySQL and Oracle have no global read
(NotSupportedException). Rows of the domain table are never updated except by a delete: an update would give a SQL
Server row a new rowversion.
Subscriptions. Subscriptions poll, 100 events at a time (an all-streams subscription:
SubscriptionOptions.BatchSize); a PollingInterval of zero or less polls every millisecond, and one above
uint.MaxValue - 1 milliseconds (about 49.7 days, the longest Task.Delay) is refused (ArgumentOutOfRangeException).
Each poll runs in its own DI scope and unit of work (when the store was resolved from DI), so a subscription outlives
the scope that created it. A failing poll is logged (Warning) and retried after a backoff (the polling interval doubled
per failure, capped at 30 s). A stream subscription's position only advances past a delivered event, so a failing
callback sees the same event again; an all-streams subscription follows its poison policy (below). Only disposal, or
the cancellation token given at subscription, ends a subscription; disposing it from its own callback is allowed (it
returns at once, and the subscription ends after that callback). Disposed from elsewhere, or ended by its token, a
subscription waits for the delivery in flight only: the rest of the batch is not delivered, and an all-streams
subscription does not save it, so the next holder delivers it again from the last saved checkpoint. A stream
subscription keeps its position in memory: it starts again at FromVersion.
SubscribeToAllStreams delivers the events of every stream in commit order (see Global order) to a named,
durable subscription:
await using IAsyncDisposable subscription = store.SubscribeToAllStreams(new SubscribeToAllStreamsRequest
{
Name = "order-projection",
StartFrom = SubscriptionStartFrom.Beginning, // used when no checkpoint exists (or End)
Options = new SubscriptionOptions { OnError = SubscriptionErrorPolicy.Retry(10) },
OnEvent = async (envelope, ct) => await project.ApplyAsync(envelope.Event, envelope.Position, ct),
}, ct);
- Checkpoint. The
EventSubscriptionsrow of the name holds the position of the last delivered event, saved after each batch (SubscriptionOptions.BatchSize, 100) in a statement of its own: a restart continues after it, and a batch interrupted by a crash is delivered again (at least once β make the callback idempotent). The name is unique in the database: theEventSubscriptionstable is shared by every event store and every service using theEventschema of that database, so two of them subscribing under one name share one checkpoint and one lease and skip or replay each other's events. Give each store or service names of its own, for example prefixed with its name (billing:order-projection). - One instance per name. An instance delivers only while it holds the row's lease (
LeaseDuration, 30 s, at mostint.MaxValueseconds), taken and renewed on database time at every poll and, inside a long batch, with the checkpoint once half the lease has elapsed, between two deliveries (a batch stops when its lease is lost); another instance with the same name waits, and takes over when the lease is released (disposal, or the end of the subscription's cancellation token) or expires. The lease is renewed between deliveries only: keep each delivery well under half the lease, or a delivery that outlasts it lets another instance deliver at the same time (the late holder's checkpoint save then fails, so the checkpoint stays right). - Poison events. A failing delivery is retried after a backoff; after
MaxAttempts,Retrystops the subscription (EventSubscriptionStatus.Faulted, with its error) untilIEventSubscriptionStore.ResumeAsync(name), andSkipToDeadLetterwrites the event's id, position and error toEventSubscriptionDeadLettersand goes on. - Administration.
IEventSubscriptionStore(registered byAddXEventStore()) lists the subscriptions with their position, status, owner, lease, failures and last error, moves a checkpoint (ResetPositionAsync, taken at the next poll: it also releases the lease, so a batch in flight stops and never saves over it, even when it started from that very position) and resumes a faulted one. Names starting with$are reserved: listed by neither, refused by both (ArgumentException). A row whose status or position the library cannot read makesListAsyncthrowInvalidOperationExceptionnaming it.
Snapshots
An aggregate implementing IOriginator (System.States) is snapshotted by AggregateStore every time an append
crosses a multiple of SnapshotOptions.SnapshotFrequency events (default 50); SnapshotOptions.IsSnapshotEnabled = false, or a frequency of 0 or less, disables snapshots. The snapshot is written in the append's transaction,
under a savepoint: a snapshot that fails (a memento the JSON context does not know, a database error) is logged
(Warning) and undone alone β the append is stored β unless the database ended the whole transaction with it (a
deadlock victim, XACT_ABORT, a SQLite I/O error): the append then fails with that error. A cancelled append fails
whatever its snapshot reports. In an ambient System.Transactions transaction, which takes no savepoint, only a memento
that cannot be written is logged; a database error fails the append. After a snapshot is written, the aggregate's older
snapshots are deleted down to SnapshotOptions.Keep (default 2; 0 or less keeps them all;
IEventStore.PruneSnapshotsAsync), under a savepoint of their own: a prune that fails is logged (Warning) and keeps
the snapshot.
services.Configure<SnapshotOptions>(options => options.SnapshotFrequency = 100);
The snapshot stores the memento by its own type, under its [CacheType] name (else its type name), with the stream
version and the business version it was taken at. Reading restores the memento, then the store sets the aggregate's
identity and versions (on an Aggregate; an IAggregate of your own sets them in Restore) and replays the events
after it. A snapshot whose stream version (-1) or business version (0)
is unknown is ignored and the stream is replayed in full. The memento type must therefore be registered with the type
resolver (mark it [CacheType]: the generated AddX{Assembly}CacheTypes() of its project registers it) and be known to the JSON
serializer context. When an aggregate is read (IAggregateStore.ReadAsync, IEventStore.ReadFromLatestSnapshotAsync),
a latest snapshot that cannot be read β an unregistered memento, a payload that no longer deserializes β is logged
(Warning) and the stream is replayed in full: a memento's shape can change freely, the next snapshot replaces it.
GetLatestSnapshotAsync still throws InvalidOperationException for an unregistered memento. A truncated stream relies
on its snapshot: when that snapshot cannot be read, the read throws InvalidOperationException saying so (the snapshot's
failure is its inner exception) rather than replaying a stream whose first events are gone.
[CacheType("Orders.OrderMemento")]
public sealed record OrderMemento(string? OrderNumber, decimal TotalAmount) : IMemento;
IEventStore.AppendSnapshotAsync and GetLatestSnapshotAsync (the newest visible snapshot of a stream by stream
version, then insertion order, or null) are available for custom stores. Reads, truncation, pruning and
GetLatestSnapshotAsync agree on that latest snapshot (a snapshot type that does not store its stream version is
ordered by insertion only). Reads use the latest snapshot by stream version only: a snapshot appended at a stream's
head with BusinessVersion 0 (unknown) hides the restorable one before it, and on a truncated stream it makes the
aggregate unreadable (see Truncating). ReadFromLatestSnapshotAsync(streamId) returns the latest snapshot and the
events after its stream version (the whole stream without one) as a StreamFromSnapshot: the data store reads both
queries at once β one round trip where the provider batches commands β when its snapshot rows store their stream
version, and the aggregate store reads a snapshotted aggregate through it; when a newer snapshot was committed between
the two queries, the events after the snapshot read are read again. Its default implementation, for a store of your
own, reads the snapshot then the events.
ποΈ Aggregates
using System.Events.Domain;
using System.Events.DomainEvents;
using System.States;
public sealed record ItemAddedEvent : DomainEvent
{
public required decimal Price { get; init; }
}
public sealed class OrderAggregate : Aggregate, IAggregateFactory<OrderAggregate>, IOriginator
{
public OrderAggregate()
{
On<OrderCreatedEvent>(@event => { OrderNumber = @event.OrderNumber; TotalAmount = @event.Amount; });
On<ItemAddedEvent>(@event => TotalAmount += @event.Price);
}
public string? OrderNumber { get; private set; }
public decimal TotalAmount { get; private set; }
public static OrderAggregate Create(CreateArgs args) => new();
public static OrderAggregate Open(Guid id, string orderNumber, decimal amount)
{
var aggregate = new OrderAggregate();
// The first event carries the stream id; the aggregate assigns versions (0, 1, ...).
aggregate.AppendEvent(new OrderCreatedEvent { StreamId = id, OrderNumber = orderNumber, Amount = amount });
return aggregate;
}
public void AddItem(decimal price) => AppendEvent(new ItemAddedEvent { StreamId = StreamId, Price = price });
public IMemento Save() => new OrderMemento(OrderNumber, TotalAmount);
public void Restore(IMemento memento)
{
var state = (OrderMemento)memento;
(OrderNumber, TotalAmount) = (state.OrderNumber, state.TotalAmount);
}
}
// Save the aggregate: persists its events (and a snapshot when due), publishes them to the domain consumers and
// enqueues the integration events, in one transaction.
IAggregateStore<OrderAggregate> store = scope.ServiceProvider.GetRequiredService<IAggregateStore<OrderAggregate>>();
var order = OrderAggregate.Open(Guid.CreateVersion7(), "ORD-001", 100m);
order.AddItem(25m);
await store.AppendAsync(order, integrationEvents: [new OrderSubmittedIntegrationEvent(order.StreamId, order.TotalAmount)]);
// Read the aggregate
order = await store.ReadAsync(order.StreamId, ct);
Aggregate rules
- Handlers are registered with
On<TEvent>(Action<TEvent>), by the event's exact type; a secondOnfor the same type is ignored. Applying an event without a handler throwsInvalidOperationException. - The first event must carry a non-empty
StreamId(InvalidOperationExceptionotherwise); later events may leave it empty, the aggregate's id is then used. An event of another stream throwsArgumentException. An event without aStreamNamegets the aggregate's (StreamName, the type name by default, virtual). AppendEvent(orAppendVersioningEvent, orAppendVersioningEvent<TEvent>(Func<long, TEvent>)which receives the next version) stamps the next version and runs the handler. An event appended from inside a handler gets the next version, after the event being handled; while the history is replayed, such an append is ignored (the history already holds it). A handler that throws takes back its event and every event it raised. An event whoseEventIdis already uncommitted is ignored.StreamVersionis the version of the last event, uncommitted included (-1for a new aggregate);ExpectedStreamVersionis the persisted one, which the store appends against.IsEmptyis true until the aggregate has an id.- A replayed history must be contiguous: an event whose version is not the one after the version reached (the
snapshot's, or -1) throws
EventStreamCorruptedException(StreamId,ExpectedVersion,ActualVersion). BusinessVersionstarts at 1 and grows by one for each eventIsSignificantBusinessEventreturns true for (false by default); overrideUpdateBusinessVersionFromEventfor another rule. It runs for appended and replayed events alike.IEventSourcingdeclaresGetUncommittedEvents(),DequeueUncommittedEvents(),MarkEventsAsCommitted(),LoadFromHistory(...)(which sorts a history given out of order),AppendEventandAppendVersioningEvent; the store usesGetUncommittedEvents,MarkEventsAsCommitted,LoadFromHistoryand theReplay(history)extension (IEventSourcingExtensions).
Aggregate store
AddXAggregateStore<TAggregate>() registers IAggregateStore<TAggregate> (scoped); AddXAggregateStore() registers
the open generic AggregateStore<> for every aggregate, and AddXAggregateStore(Type) a custom open generic store. Each
also registers the events unit of work and the scheduler trigger. AggregateStore<TAggregate> needs IEventStore,
IOutboxStore, IEventPublisher, IDomainEventEnricher and IPendingIntegrationEvents.
ReadAsync(streamId)restores the newest snapshot when snapshots apply, else replays the whole stream. An empty id throwsArgumentOutOfRangeException; a stream with no events throwsValidationException.AppendAsync(aggregate)andAppendAsync(aggregate, integrationEvents)run in one transaction of the events unit of work: the uncommitted events (enriched byIDomainEventEnricher) are appended againstExpectedStreamVersion, a snapshot is written when due, the events are published throughIEventPublisher(the consumers run in the store's scope, so what they add toIPendingIntegrationEventsjoins this transaction), then the given integration events, those queued inIPendingIntegrationEventsbefore the append and those the consumers added are enqueued in the outbox. An append with nothing to write returnsAppendResult.Empty.- After the commit the aggregate's events are marked committed, and the scheduler is signalled once the outbox rows are visible (after the caller's transaction when the append joined one; never when it rolls back). A failing signal is logged; the next poll delivers the events anyway.
- A failed append (a concurrency conflict, a consumer that throws, a cancellation) rolls back and leaves the
aggregate's events uncommitted and the pending integration events queued: retrying
AppendAsyncresends everything. A failing rollback is logged and the append's own failure is rethrown.
Aggregate state machine
AggregateStateContext<TState> is an aggregate whose state is a State<TContext> (System.States):
public abstract class OrderState : State<OrderStateContext>;
public sealed class DraftState : OrderState;
public sealed class SubmittedState : OrderState;
public sealed class OrderStateContext() : AggregateStateContext<OrderState>(new DraftState())
{
public void Submit() => TransitionToState(new SubmittedState());
protected override bool CanTransitionTo(OrderState newState) => CurrentState is DraftState;
}
The initial state enters its context without a transition. TransitionToState throws InvalidOperationException when
CanTransitionTo refuses, or when another thread changed the state meanwhile; OnStateTransitioning and the
StateTransitioning event run before the change (one of them throwing vetoes it), OnStateTransitioned and
StateTransitioned after it (raise the domain events of the change there). CurrentState is thread-safe; the hooks run
outside the lock.
π Correlation and Enrichment
AddXEventContextAccessor() registers ICorrelationContextAccessor (an AsyncLocal accessor). Open a scope to
correlate everything written in a logical call path:
var accessor = app.Services.GetRequiredService<ICorrelationContextAccessor>();
using IDisposable _ = accessor.BeginScope(new CorrelationContext
{
CorrelationId = Guid.CreateVersion7().ToString("N"),
CausationId = Guid.CreateVersion7().ToString("N"),
});
DefaultDomainEventEnricher(AddXDomainEventEnricher()) sets a domain event's missingCorrelationIdandCausationIdfrom the context; the aggregate store enriches every event it appends.IntegrationEventEnricher(AddXIntegrationEventEnricher()) keeps the ids already on an integration event, then takes those of the domain event anIntegrationEvent<TDomainEvent>carries, then those of the context; the outbox store enriches every event it enqueues.AddXDomainEventEnricher<T>()andAddXIntegrationEventEnricher<T>()register your own (scoped; the first registration wins).
While a consumer run by the integration event receiver runs, and while a subscription callback runs, the ambient
context is the event's correlation id with the event's id as the causation id: the events it appends or enqueues carry
them, and so do the HTTP calls it makes through Xpandables.Rests (X-Correlation-Id, X-Causation-Id).
π¨ Outbox/Inbox Pattern
Outbox
public sealed record OrderSubmittedIntegrationEvent(Guid OrderId, decimal Total) : IntegrationEvent;
// IOutboxStore is registered by AddXOutboxStore() (or AddXAllEventStores()).
IOutboxStore outbox = scope.ServiceProvider.GetRequiredService<IOutboxStore>();
await outbox.EnqueueAsync([new OrderSubmittedIntegrationEvent(orderId, 125m)], ct);
// A worker claims a batch for a lease; the claim counts as an attempt. Completing (or failing) with the claim id only
// touches rows still held by this claim: a worker whose lease expired cannot overwrite the row another worker now holds.
OutboxClaim claim = await outbox.ClaimAsync(maxEvents: 10, lease: TimeSpan.FromMinutes(5), maxAttempts: 5, ct);
if (claim.Events.Count > 0)
{
// ... publish them, then:
await outbox.CompleteAsync(claim.Events.Select(e => new CompletedOutboxEvent(e.EventId) { ClaimId = claim.ClaimId }), ct);
}
Integration events are usually enqueued by the aggregate store, in the append's transaction (enriched by
IIntegrationEventEnricher), and delivered by the scheduler. EnqueueAsync,
CompleteAsync and FailAsync throw ArgumentOutOfRangeException for an empty list.
ClaimAsynctakes, in enqueue order and on the database's clock, pending events whoseNotBeforeis reached, failed events whose retry is due, and events whose last claim's lease expired (the worker died or hung). It is one statement (SQL Server, PostgreSQL, SQLite) that reads its candidates without waiting for the rows another worker's claim holds (UPDLOCK, READPAST;FOR UPDATE SKIP LOCKED) and marks them claimed at once: two workers never take the same row, and neither waits for another's claim (on SQL Server under lockingREAD COMMITTEDa claim may wait on a row another statement writes, and a deadlock is retried in a new transaction:DataRetryOptions). On SQL Server the claim seeks the rows it holds byKeyId(FORCESEEK): a table of your own needs that index, and itsPartitionKeymust beVARCHAR(100)as in the scripts. An event with aPartitionKeyis claimed only when no earlier event of its key is unfinished (pending, failing, claimed or parked) outside the claim. It returns at most 1000 events asIntegrationEventEnvelopes (the stored JSON, name and version), with their attempt counts (OutboxClaim.AttemptCounts);OutboxClaim.Contendedsays it returned fewer than asked while claimable events remain.- A parked event holds the later events of its key back until it is requeued or purged;
SchedulerOptions.SkipParkedInOrderinglets them pass it. FailAsyncschedules the retry, on the database's clock, afterSchedulerOptions.EventRetryBaseDelay(20 s), doubled per attempt up toEventRetryMaxDelay(10 min), and returns the ids of the rows it updated. An event that failedmaxAttemptstimes is not claimed again: it is parked (CountParkedAsync(maxAttempts)counts them).ReleaseAsync(claimId, eventIds)returns claimed events that were never attempted: they are pending again and the attempt is not counted.
Ordering
An integration event carries a PartitionKey (at most 100 characters; WithPartitionKey(key), or PartitionKey = β¦
on an IntegrationEvent): the events of one key are delivered one after another, in the order they were enqueued, and
an event waits while an earlier event of its key is not delivered. The aggregate store gives an event without a key the
stream id of the aggregate it appends, so the events of one aggregate arrive in order; a scheduled event (NotBefore)
keeps no key, so that it does not hold back the stream's later events until its time. An event without a key is
delivered without order. EnqueueAsync throws ArgumentException for a longer key, before writing anything (inside an
aggregate's append, its transaction rolls back). Keys are compared as SQL Server's default collation does, ignoring case
and trailing spaces: Order-1 and order-1 are one key; give keys that differ in more than that.
Scheduled events
An integration event with a NotBefore waits in the outbox and is delivered once that time is reached. It is written
in the transaction of the command that causes it, like any integration event, so the schedule exists only if the
command committed:
public sealed record ShipmentDue(Guid OrderId) : IntegrationEvent;
// With the aggregate's events, in the append's transaction (or from a domain event consumer, through
// IPendingIntegrationEvents):
await orders.AppendAsync(order, [new ShipmentDue(order.Id) { NotBefore = order.ShipOn }], ct);
- Storage.
EnqueueAsyncstoresNotBeforein UTC in the row'sNextAttemptOn, andClaimAsynctakes a pending row only once the database's clock reached that time; the existing(Status, NextAttemptOn, Sequence)index serves both. A waiting event takes no place in a batch, and the events after it are not held up.null,defaultor a time already past is delivered on the next run. Once claimed, the event follows the usual lease, retries and parking. - On time. After a run that did not fill its batch, the scheduler reads the next due time
(
IOutboxStore.GetNextDueOnAsync, one index seek), once the run's consumers wrote what they write: a next occurrence written by this run is in it. The hosted scheduler runs then instead of at its next tick, so delivery does not wait forSchedulerFrequency. A store of your own that does not implementGetNextDueOnAsyncgets its scheduled events claimed at the ticks; one that implementsClaimAsyncmust apply theNotBeforerule. - Cancelling. Nothing to delete: the consumer reads the current state when the event arrives and does nothing when the work is no longer due (the order was cancelled, the date moved).
- Repeating. The consumer writes the next occurrence itself (
NotBefore = previous + period), with the aggregate it appends or withIOutboxStore.EnqueueAsync, both through the events unit of work. Register it withAddXIntegrationEventConsumerand the events unit of work: delivery is at least once, and an occurrence delivered again β its completion was lost, its lease expired β would otherwise write a second next occurrence, and the series would then run twice. The inbox records the receipt, the consumer's writes (the next occurrence included) and the completion in one transaction, so the event delivered again is aDUPLICATEand writes nothing.
Dead letters
An outbox event that failed MaxSchedulerRetries times is parked; an inbox receipt that failed
InboxOptions.MaxAttempts times is suspended. Neither is retried until it is requeued:
IReadOnlyList<ParkedOutboxEvent> parked = await outbox.ListParkedAsync(skip: 0, take: 50, ct);
await outbox.RequeueAsync(parked[0].EventId, ct); // pending again; attempts, error, due time reset
await outbox.RequeueAllParkedAsync(ct);
await outbox.PurgeParkedAsync(DateTimeOffset.UtcNow.AddDays(-30), ct); // never delivered
IReadOnlyList<SuspendedInboxEvent> suspended = await inbox.ListSuspendedAsync("OrderHandler", 0, 50, ct);
await inbox.RequeueAsync(suspended[0].EventId, "OrderHandler", ct); // the event's next delivery runs the consumer
await inbox.RequeueAllSuspendedAsync(consumer: null, ct);
await inbox.PurgeSuspendedAsync(DateTimeOffset.UtcNow.AddDays(-30), consumer: null, ct);
The stored error (ErrorMessage) is the exception's type and message, then the first 4 000 characters of its
ToString(). An event held under a live lease (claimed again) is not parked: it is neither listed, requeued nor
purged. A requeued event keeps its place in its partition key's order, and a parked event holds the later events of its
key back until it is requeued or purged. An inbox receipt suspended for a consumer makes the relay's deliveries of that
event deferrals, which count once MaxDeferrals is passed: requeue the receipt, then the parked outbox event. A store of
your own throws NotSupportedException for these members unless it implements them.
Retention
services.AddXEventRetention(options =>
{
options.OutboxProcessed = TimeSpan.FromDays(7); // delivered outbox events; null keeps them
options.InboxProcessed = TimeSpan.FromDays(30); // processed inbox receipts
options.SubscriptionDeadLetters = TimeSpan.FromDays(30); // dead letters of the all-streams subscriptions
});
EventRetentionService (hosted) deletes, every Interval (1 hour), the delivered outbox events, the processed inbox
receipts and the subscription dead letters older than their retention, compared with the database's clock, by
batches of BatchSize (1 000) with a Pause (1 s) between two. The command idempotency entries of
Xpandables.AspNetCore.Net are purged on the same schedule once expired (IdempotencyEntries). One instance purges at a
time: it holds the lease row $retention:Event.EventOutbox of Event.EventSubscriptions (named after the outbox table it purges; stopping releases it). A purge of your own registers as a
scoped IRetentionPurge. Parked and suspended rows are not purged here: see Dead letters. An inbox
receipt is the inbox's memory of a delivery: once it is purged, a redelivery of that event runs the consumer again, so
keep InboxProcessed above the longest time a broker may redeliver.
Inbox
// IInboxStore is registered by AddXInboxStore() (or AddXAllEventStores()).
IInboxStore inbox = scope.ServiceProvider.GetRequiredService<IInboxStore>();
// Each consumer of an event has its own inbox row: two consumers of one event are both received.
InboxReceiveResult result = await inbox.ReceiveAsync(integrationEvent, consumer: "OrderHandler",
visibilityTimeout: TimeSpan.FromSeconds(30), cancellationToken: ct);
if (result.Status == EventStatus.ACCEPTED)
{
try
{
await HandleAsync(integrationEvent, ct);
await inbox.CompleteAsync(ct, new CompletedInboxEvent(integrationEvent.EventId, "OrderHandler") { ClaimId = result.ClaimId });
}
catch (Exception exception)
{
await inbox.FailAsync(CancellationToken.None,
new FailedInboxEvent(integrationEvent.EventId, "OrderHandler", exception.ToString()) { ClaimId = result.ClaimId });
throw;
}
}
| Status | Meaning |
|---|---|
ACCEPTED |
Process it, then CompleteAsync (or FailAsync). |
DUPLICATE |
Already processed by this consumer (a row with an unknown status is reported the same way). |
PROCESSING |
Another receiver holds it; RetryAfter is its lease expiry (on the database's clock). An expired lease is reclaimed. |
ONERROR |
It failed and waits for its retry at RetryAfter (on the database's clock). |
SUSPENDED |
It failed InboxOptions.MaxAttempts times (default 10); a warning is logged and it is not processed again. |
A blank consumer name throws ArgumentException; CompleteAsync and FailAsync with no event throw
ArgumentOutOfRangeException. Of two receivers retrying the same failed event, only one gets ACCEPTED. A first receive
that loses the insert race to a concurrent one reports the winner's state, as a receive that reads the row would
(PROCESSING, or DUPLICATE, SUSPENDED or ONERROR when the winner already settled or failed it); under a snapshot
(SQL Server SNAPSHOT, PostgreSQL REPEATABLE READ or SERIALIZABLE), or when the database rolled the transaction back, the
winner cannot be read and the result is PROCESSING with no RetryAfter. Inside a transaction, the insert runs under
a savepoint, so the transaction can still commit after losing the race. On PostgreSQL inside an ambient
System.Transactions transaction, which takes no savepoint, a receipt that loses the race reports PROCESSING without
a RetryAfter, and the transaction scope must be disposed without completing it.
An ACCEPTED result carries a ClaimId: pass it to CompletedInboxEvent/FailedInboxEvent so that a receiver whose
lease expired cannot overwrite the row another receiver now owns. The lease is the visibility timeout, else
InboxOptions.Lease (default 5 minutes): set it above the longest time a consumer takes. A failure retries after the
scheduler's EventRetryBaseDelay, doubled per attempt up to EventRetryMaxDelay Β±20 % (UseBackoffJitter). Leases and
retry times are written and compared on the database's clock, as the outbox's are (a lease is capped at about 24.8
days). Every receive that reclaims an event counts as an attempt, so an event whose receivers keep dying is suspended
too. ReleaseAsync gives back the receipt of a consumer that was cancelled (pass its ClaimId in a
ReleasedInboxEvent): the attempt is not counted and the event can be received again at once.
services.Configure<InboxOptions>(options => { options.MaxAttempts = 5; options.Lease = TimeSpan.FromMinutes(2); });
Integration event consumers
public sealed class OrderSubmittedHandler : IEventConsumer<OrderSubmittedIntegrationEvent>, IInboxConsumer
{
public string Consumer => "OrderHandler"; // optional: the inbox name; without IInboxConsumer, see below
public Task ConsumeAsync(OrderSubmittedIntegrationEvent @event, CancellationToken ct) => Task.CompletedTask;
}
services.AddXIntegrationEventConsumer<OrderSubmittedIntegrationEvent, OrderSubmittedHandler>();
Every consumer of an integration event runs through the inbox: the generated AddX{Assembly}EventConsumers() registers
each one with AddXIntegrationEventConsumer, which wraps it in InboxEventConsumerBehavior and registers the
IIntegrationEventReceiver; register an IInboxStore (AddXInboxStore()). A redelivered event runs only the consumers
that have not completed it.
The inbox name is IInboxConsumer.Consumer when the consumer implements it (a blank one falls back), else
"{consumer type} -> {event type}", both written by Type.ToString() (Shop.Audit`1[Shop.Paid] -> Shop.Paid): no
assembly qualification, so the name does not change with the assembly version, and one name per event type, so a
consumer of an event and of its base type or interface runs for both. A default name longer than the Consumer column
(500) keeps its first 435 characters, a # and the lowercase hex SHA-256 of the whole name. Renaming the class, its
namespace or the event changes the default name and so its inbox rows: give a consumer a stable Consumer when events
may be redelivered across such a deployment. An explicit Consumer is the same for every event type the class consumes,
so one event delivered to two of its contracts runs the first only: give such a class no IInboxConsumer. On SQL Server
the Consumer column has the database's default collation, which usually ignores case: names that differ only in case
share a key there. A consumer of a contract that domain and integration events share (IEventConsumer<IEvent>) is
registered as a domain consumer and runs outside the inbox, also for integration events; consume the integration
event type to get the inbox. IEventSubscriber.Subscribe<T> delegates run for events published in process; the relay
delivers integration events through the receiver, which runs the registered consumers only.
AddXEventConsumer registers a consumer of an integration event (TEvent is an IIntegrationEvent) the same way as
AddXIntegrationEventConsumer: through the inbox, the factory building the consumer the behavior wraps. The consumer is
registered once whichever of the two registers it, in whatever order. Its type must be concrete (the inbox names it by
its type): an abstract or interface consumer type throws InvalidOperationException. A consumer of a domain event is
registered directly.
The behavior receives the event with the inbox's lease, runs the consumer on ACCEPTED and completes it, or records the
failure (with CancellationToken.None) and rethrows. A consumer cancelled through its token (the host stopping, or the
relay's EventProcessingTimeout) releases its receipt instead: the inbox counts no attempt and the event is received
again (the relay still counts a timeout as an outbox attempt). It returns for a DUPLICATE
and throws InboxEventDeferredException (EventId, Consumer, Status, RetryAfter) for PROCESSING, ONERROR
and SUSPENDED: the event was not processed, so the message must not be acknowledged.
With the events unit of work (EventStoreServiceKeys.UnitOfWork, registered by AddXEventUnitOfWork), the receipt,
the consumer and the completion run in one transaction and commit once: what the consumer writes through that unit of
work (repositories of the same database, an aggregate store's append, which joins the transaction) and the inbox row are
kept or lost together. A failing consumer is rolled back to a savepoint, its failure recorded, and the transaction
committed; a failing completion or commit throws, nothing is kept, and the event is delivered again. A consumer writing
to another database commits on its own, as without the unit of work.
β° Background Scheduler
Scheduler (AddXScheduler(), singleton IScheduler) claims outbox events and delivers each one to exactly one
target: the registered IEventBus, else the in-process IIntegrationEventReceiver; HostedScheduler
(AddXHostedScheduler()) runs it as a background service.
builder.Services.Configure<SchedulerOptions>(options =>
{
options.BatchSize = 20; // at most SchedulerOptions.MaxBatchSize (1000)
options.MaxConcurrentProcessors = 4; // read at each run
options.SchedulerFrequency = 5_000; // ms
options.EventProcessingTimeout = 30_000; // ms, per event
options.MaxSchedulerRetries = 5; // attempts before an event is parked
options.CircuitBreakerFailureThreshold = 5;
options.CircuitBreakerTimeoutMs = 30_000;
});
SchedulerOptions |
Default | Purpose |
|---|---|---|
IsEventSchedulerEnabled |
true |
When false, runs do nothing |
SchedulerFrequency |
15000 ms |
Polling period (1000β300000); a change restarts the timer |
BatchSize |
100 |
Events claimed per run (1β1000) |
MaxConcurrentProcessors |
processor count | Events delivered in parallel (1β50); one partition key's events one after another |
EventProcessingTimeout |
30000 ms |
Bound of one event's publication |
ClaimLease |
null |
Claim lease; null computes one (below); zero or negative throws |
MaxSchedulerRetries |
5 |
Attempts after which an event is parked (1β100) |
SkipParkedInOrdering |
false |
A parked event lets the later events of its partition key pass |
EventRetryBaseDelay / EventRetryMaxDelay |
20 s / 10 min |
Retry delay of a failed event, doubled per attempt (outbox and inbox) |
MaxDeferrals |
100 |
Deferrals of an event that do not count as attempts (1β10000) |
DrainTimeout |
20 s |
How long stopping waits for the events in flight (no new event starts) |
CircuitBreakerFailureThreshold |
10 |
Failed runs that open the breaker |
CircuitBreakerTimeoutMs |
60000 ms |
Time the breaker stays open before a half-open probe |
BackoffBaseDelayMs / BackoffMaxDelayMs |
1000 / 300000 ms |
Host loop backoff after failed runs |
UseBackoffJitter |
true |
Jitter on the backoff (uniform between the base delay and the ceiling) and Β±20 % on the retry delay of a failed event |
EnableMetrics |
true |
Collects run counts and durations (logged when the scheduler is disposed) |
EnableHealthChecks |
true |
When false, the health check always reports healthy |
UnhealthyAfterConsecutiveFailures |
3 |
Failed runs after which the health check reports unhealthy |
The ranges are [Range] annotations: they are checked only when you validate the options (for instance
services.AddOptions<SchedulerOptions>().ValidateDataAnnotations()). The scheduler itself caps BatchSize at
MaxBatchSize and uses at least one processor.
- Claim and lease. Each run claims up to
BatchSizeevents forClaimLease; when it is not set, the lease ismax(5 min, (ceil(BatchSize / MaxConcurrentProcessors) + 1) Γ EventProcessingTimeout), long enough to publish the batch and complete it at the end of the run. AClaimLeaseset by hand must leave that time too. The claim runs in its own scope, released before publishing. - Delivery. Events are delivered in parallel up to
MaxConcurrentProcessors, one partition key's in order (below), each in its own DI scope (the ambient scope of its consumers), to theIEventBuswhen one is registered, else to theIIntegrationEventReceiver; each delivery is bounded byEventProcessingTimeouteven when its consumer or bus ignores the cancellation token. A timeout is a failure, and an event the receiver cannot read (an unknown name, a missing upcaster) fails like any other: it is retried and eventually parked. - Order. The events of one partition key run one after another, in their order, in one worker; keys, and events
without a key, run in parallel up to
MaxConcurrentProcessors. An event that fails holds its key back: the key's later events of the run are released (pending again, attempt not counted) and wait for its retry; other keys go on. A key's later events also stop starting once they could outlast the claim's lease (after lease β 2 ΓEventProcessingTimeout): they are released for the next run. - Completion. The events a run published are completed in one call after the run, in their own scope, even if
shutdown starts meanwhile. A process that stops between publishing and completing leaves them claimed: when the lease
expires they are published again, and a consumer registered with
AddXIntegrationEventConsumerreceives each of them as aDUPLICATEand does not run again. A completion that fails is logged, and the lease expiry recovers the events the same way. - Retries and parking. A failed event is retried after
EventRetryBaseDelay, doubled per attempt up toEventRetryMaxDelay. AfterMaxSchedulerRetriesattempts it is parked: a warning is logged,Scheduler.ParkedEventscounts it, and the health check reportsDegradedwhile the outbox holds parked events. The failures of a run are recorded in one call, and an event is parked only when its failure matched its row (a worker whose lease expired does not hold it any more). The retry delay is spread over Β±20 % (UseBackoffJitter), so events that failed together are not retried together. - Deferral. When the receiver reports
InboxEventDeferredException(a consumer's inbox row is held by another receiver, waits for its retry, or is suspended), the event is not failed: it is rescheduled at the exception'sRetryAfter(else afterEventRetryBaseDelay), the claim's attempt is taken back, and the row'sDeferralCountgrows. PastMaxDeferralsdeferrals each one counts as an attempt, so an event deferred for ever is parked. A deferral holds back its partition key like a failure, and counts neither for health nor for the circuit breaker. - Health. Runs are judged on the events claimed for their first attempt: a run fails when more than half of them
failed;
ConsecutiveFailuresthen grows (health goesDegraded, thenUnhealthyafterUnhealthyAfterConsecutiveFailures), and it is reset by a run that published without failing (or by an empty poll once the failed events' retries are due). A run that throws also counts. Retries of an event that already failed do not fail a run: a poison event is reported through parking (Degraded), not as an outage. A poll that finds nothing does not reset the count while failed events wait for their retry. - Circuit breaker. A run that throws, or in which every first attempt failed and nothing published, counts toward
the breaker; at
CircuitBreakerFailureThresholdit opens and runs are skipped forCircuitBreakerTimeoutMs. Then one run probes (half-open): it closes the breaker when anything published (or when it finds nothing to publish and no retry is pending), and reopens it when it throws or publishes none of the events it claimed while one failed; a probe whose events were all deferred settles nothing, and the next run probes again. An event whose stored name or version cannot be read fails like any delivery, so a batch made only of such events (an event type removed) counts as a failed run until they wait for their retry. - Backoff. After a failed run the hosted loop waits
SchedulerBackoff.GetDelay(ConsecutiveFailures, options):BackoffBaseDelayMsdoubled per consecutive failure, capped atBackoffMaxDelayMs, with jitter between the base delay and that ceiling. - Shutdown. Once the hosted scheduler starts stopping, no new claim and no event start (a claim already running
completes, and its events are released): not a new partition key, not a
key's next event. The events in flight end within
DrainTimeout(default 20 s) or the host's shutdown timeout, whichever comes first, and are then cancelled. Stopping waits for the run to complete what it delivered and to release the rest: events not started and events cancelled in flight are pending again, attempt not counted. KeepDrainTimeoutbelow the host'sShutdownTimeoutand the orchestrator's grace period. The default leaves about 10 s under the usual 30 s, so that the release runs before the process is killed.IScheduler.ScheduleAsync(cancellationToken, stoppingToken)carries both signals for a host of your own. - Wake-up.
IEventSchedulerTrigger.Signal()(called by the aggregate store once an append's outbox rows are committed) wakes the loop at once, also during a backoff; signals raised before the loop observes them collapse into one. The periodic poll still runs, so a missed signal only delays delivery. - Backlog.
IScheduler.ScheduleAsyncreturnstruewhen the run claimed a full batch, or when another worker's claim cut its claim short (OutboxClaim.Contended): more events may be waiting, and the host runs again at once instead of waiting for a signal or the next tick (a backoff still applies first). A claim that finds nothing while it stays contended runs again at once three times in a row at most, then waits for the next tick. - Scheduled events.
IScheduler.NextDueOnis the time the last run read, after publishing, for the next scheduled event; when it comes before the next tick, the host runs at that time (a signal still wakes it sooner). A failing read is logged and leaves the events to the next tick. - Options. Both the scheduler and the host read the options monitor: a configuration change applies from the next run.
- Clock. Leases, retry times and due times of the outbox and the inbox are written and compared on the database's
clock (SQL Server
SYSUTCDATETIME(), PostgreSQLstatement_timestamp(), SQLitestrftime('now')), so instances whose clocks differ agree on them. A registeredTimeProviderdrives the timeouts, the breaker, the polling timer, the backoff wait and theCreatedOn,UpdatedOnandDeletedOnstamps. Times read back are UTC, whatever kind the provider returns.
Health check
builder.Services.AddXSchedulerHealthCheck(name: "scheduler", failureStatus: HealthStatus.Unhealthy, "ready");
SchedulerHealthCheck reports Healthy while runs succeed; Degraded after a failed run, while the outbox holds
parked events (parkedEvents), while its oldest deliverable event has waited longer than
SchedulerHealthOptions.MaxPendingAge (5 minutes; oldestPendingAgeSeconds: the relay is behind, or a partition key is
held back), or while an all-streams subscription is faulted (faultedSubscriptions), and also when the outbox or the
subscriptions cannot be read; Unhealthy after UnhealthyAfterConsecutiveFailures consecutive failed runs
(consecutiveFailures, unhealthyAfter). With EnableHealthChecks or IsEventSchedulerEnabled false it reports
healthy, so it can stay registered. The check returns its own statuses; failureStatus is what the health-check system
reports if the check throws. services.Configure<SchedulerHealthOptions>(o => o.MaxPendingAge = TimeSpan.FromMinutes(15));
sets the threshold.
ποΈ Storage
Stores and the events unit of work
The ADO.NET stores (EventStore<TDomain, TSnapshot>, OutboxStore<TOutbox>, InboxStore<TInbox>) and
AggregateStore<TAggregate> take one events unit of work, the keyed scoped IDataUnitOfWork named
EventStoreServiceKeys.UnitOfWork, so that an aggregate's events, its snapshot and its outbox rows are written in one
transaction. By default it is the scope's IDataUnitOfWork; to use another database, give it once:
// UseSqlServer needs Microsoft.Data.SqlClient registered in DbProviderFactories.
services.AddXData("events", data => data.UseSqlServer(eventsConnectionString));
services.AddXEventUnitOfWork(sp => sp.GetRequiredKeyedService<IDataUnitOfWork>("events"));
A factory replaces an earlier one; without a factory an existing registration is kept. When the events unit of work is
an instance the scope already tracks (the default one, or another registered one), the scope disposes it twice: a
custom IDataUnitOfWork must tolerate repeated disposal.
Entities and converters
The built-in entities are DataEventDomain, DataEventSnapshot, DataEventOutbox and DataEventInbox, mapped to the
Event schema's EventDomain, EventSnapshot, EventOutbox and EventInbox tables. Domain, snapshot and outbox
events are stored as JSON through the EventSerializer β written by their runtime type under their registered name and
version, read back by their stored name or alias and upcast to the type's version β and a snapshot's memento by its
[CacheType] name, read back through the ICacheTypeResolver; the inbox stores only the event's id, name, version and
correlation.
AddXEventConverters() registers the four built-in converters (EventConverterDomain, EventConverterSnapshot,
EventConverterOutbox, EventConverterInbox), except for a pair that already has one (yours, registered before with
AddXEventConverter, which replaces the converter of its pair), so calling it twice adds nothing; and
AddXEventConverterProvider() the IEventConverterProvider the stores obtain them from. A conversion failure throws InvalidOperationException; an InvalidOperationException,
ValidationException or ArgumentException raised by the conversion itself propagates as it is. A missing converter
throws
InvalidOperationException when the store is built.
The stores set a row's CreatedOn to the time of the insert, replacing the value a converter returns.
A custom entity is registered through its store type, with a converter for it (derive from
JsonEventConverter<TDataEvent, TEvent>, or implement IEventConverter<TDataEvent, TEvent>). The provider finds a converter by the entity's simple type name: the last
converter registered for an entity type wins.
services.AddXEventConverter<MyEventDomainRow, IDomainEvent, MyEventDomainRowConverter>();
services.AddXEventConverter<MyEventOutboxRow, IIntegrationEvent, MyEventOutboxRowConverter>();
services.AddXEventConverter<MyEventInboxRow, IIntegrationEvent, MyEventInboxRowConverter>();
services.AddXEventStore<EventStore<MyEventDomainRow, DataEventSnapshot>>();
services.AddXOutboxStore<OutboxStore<MyEventOutboxRow>>();
services.AddXInboxStore<InboxStore<MyEventInboxRow>>();
A custom entity must be marked [DataRecord], as the built-in ones are, or Xpandables.Data throws on first use. The
built-in entities are mapped to the default schema and table names; tables created under other names need entities of
your own mapped to them.
Supported databases (built-in SQL scripts)
| Database | Script Provider | Tables |
|---|---|---|
| SQL Server | SqlServerEventTableScripts |
EventDomain (with CommitToken ROWVERSION), EventInbox, EventOutbox, EventSnapshot, EventSubscriptions, EventSubscriptionDeadLetters |
| PostgreSQL | PostgreSqlEventTableScripts |
EventDomain (with CommitToken XID8), EventInbox, EventOutbox, EventSnapshot, EventSubscriptions, EventSubscriptionDeadLetters |
| SQLite | SqliteEventTableScripts |
EventDomain, EventInbox, EventOutbox, EventSnapshot, EventSubscriptions, EventSubscriptionDeadLetters |
IEventTableScriptProvider gives GetCreateAllTablesScript(schema, eventDomain, eventInbox, eventOutbox, eventSnapshot) and GetDropAllTablesScript(...); every argument defaults to the built-in names (Event,
EventDomain, ...). EventTableScriptProviders.SqlServer, .PostgreSql and .Sqlite hold the built-in providers.
The scripts create only missing objects.
Every event table has an EventVersion column (default 1); EventDomain and EventOutbox also have
TraceParent VARCHAR(55) and TraceState VARCHAR(256) (see Telemetry). EventSubscriptions (a named subscription's checkpoint,
lease, status and last error) and EventSubscriptionDeadLetters (indexed on CreatedOn) are created with these fixed
names in schema Event whatever the schema given to the script (the script creates the schema when missing; SQLite has
no schemas): their records are the library's own and map Event, while the four event tables follow the given schema
and names. The drop script drops them too, whatever its schema: dropping the event tables of one schema also drops the
subscriptions of every event store in the database. Since every store and service using the database shares these two
tables, a subscription name must be unique in the database across all of them (prefix it with the store's or the
service's name).
The scripts create the unique (StreamId, StreamVersion) index the concurrency check relies on, the inbox's
(KeyId, Consumer) key, the claim and retry indexes of the outbox and inbox, and index the snapshot table on
(OwnerId, StreamVersion DESC, Sequence DESC) (loading an aggregate seeks its newest snapshot, a prune walks them in
that order). On SQL Server the GUID primary keys are non-clustered and every table is clustered on its Sequence
identity, so inserts append instead of splitting pages.
On SQLite every table's Sequence is its INTEGER PRIMARY KEY AUTOINCREMENT rowid β never given twice, even after the
last rows are deleted β and the GUID key is a UNIQUE column.
On SQLite, which has no schemas, the dialect writes bare table names ("EventDomain"), so the SQLite script ignores
schema and its tables live in the main database. new SqliteDialect { SchemaAsAttachedDatabase = true } (with DataBuilder.UseSqlDialect) writes
"Event"."EventDomain" instead, for tables kept in a database attached as Event.
Scripts can be exported to disk (CreateEventTables.sql and DropEventTables.sql):
EventTableScriptExporter.ExportScripts(EventTableScriptProviders.PostgreSql, @"C:\scripts");
π§ DI Registration
All methods live in Microsoft.Extensions.DependencyInjection (IEventExtensions) and return the service collection.
| Method | Registers |
|---|---|
AddXEventContextAccessor() |
ICorrelationContextAccessor (AsyncLocalCorrelationContextAccessor, singleton) |
AddXDomainEventEnricher() / <T>() |
IDomainEventEnricher (DefaultDomainEventEnricher, scoped) |
AddXIntegrationEventEnricher() / <T>() |
IIntegrationEventEnricher (IntegrationEventEnricher, scoped) |
AddXEventPublisher(registryMode) |
The EventPublisherSubscriber singleton as itself, IEventSubscriber and (when none is registered) IEventPublisher, and the consumer registry |
AddXEventPublisher<T>(lifetime) |
Your IEventPublisher, replacing any |
AddXEventSubscriber() / <T>(lifetime) |
IEventSubscriber: the EventPublisherSubscriber singleton with its consumer registry, or yours (replacing any) |
AddXEventConsumer<TEvent, TConsumer>(factory) |
One consumer (transient) and its wrapper; for an integration event, as AddXIntegrationEventConsumer |
AddXIntegrationEventConsumer<TEvent, TConsumer>(factory) |
One consumer of an integration event wrapped in InboxEventConsumerBehavior, and the receiver; a factory replaces the consumer's registration |
AddXEventConsumerWrapper<TEvent>() |
The EventConsumerWrapper<TEvent> the static registry dispatches through |
AddX{Assembly}EventConsumers() (generated) |
Every consumer of the assembly, closed |
AddXEventBus<TEventBus>() |
IEventBus (singleton, replacing any): the relay publishes the integration events to it |
AddXIntegrationEventReceiver() |
IIntegrationEventReceiver (singleton) and the consumer registry |
AddXEventConverterProvider() / <T>() |
IEventConverterProvider (singleton) |
AddXEventConverters() |
The four built-in converters, except where a pair has one, and the EventSerializer (singleton) |
AddXEventUpcaster<TUpcaster>() |
One IEventUpcaster (singleton, once per type) |
AddXEventConverter<TDataEvent, TEvent, TConverter>() |
One converter (singleton), replacing the converter of its pair |
AddXEventStore() / <T>() |
IEventStore (scoped; EventStore<DataEventDomain, DataEventSnapshot> by default) and IEventSubscriptionStore (scoped) |
AddXOutboxStore() / <T>() |
IOutboxStore (scoped; OutboxStore<DataEventOutbox> by default) |
AddXInboxStore() / <T>() |
IInboxStore (scoped; InboxStore<DataEventInbox> by default) |
AddXAllEventStores() |
The three default stores |
AddXEventUnitOfWork(factory) |
The events unit of work the stores share (default: the scope's IDataUnitOfWork) |
AddXPendingIntegrationEvents() |
IPendingIntegrationEvents (scoped buffer drained by the aggregate store) |
AddXAggregateStore<TAggregate>() |
IAggregateStore<TAggregate> (scoped), the events unit of work and the scheduler trigger |
AddXAggregateStore() / (Type) |
The open generic IAggregateStore<> (scoped), the events unit of work and the scheduler trigger |
AddXScheduler() / <T>() |
IScheduler (singleton; Scheduler by default) and the IIntegrationEventReceiver (it needs the EventSerializer of AddXEventConverters()) |
AddXHostedScheduler() / <T>() |
IHostedScheduler as a hosted service, and the scheduler trigger |
AddXSchedulerHealthCheck(name, failureStatus, tags) |
The SchedulerHealthCheck singleton, checked under name once (a second call with the name adds nothing) |
AddXEventRetention(configure) |
EventRetentionService (hosted), the built-in IRetentionPurges and the validated EventRetentionOptions |
The stores also need Xpandables.Data (AddXData), an IJsonSerializerContext and an ICacheTypeResolver
(Xpandables.Net), and an EventTypeRegistry: the generated AddX{Assembly}CacheTypes() of each project adds to both. SnapshotOptions,
SchedulerOptions and InboxOptions are bound with services.Configure<T>(...).
π Telemetry
Xpandables.Events traces and measures through the ActivitySource and the Meter named Xpandables.Events. Nothing
is created or recorded unless something listens.
| Span | Kind | Emitted for |
|---|---|---|
append {StreamName} |
Internal | each AppendToStreamAsync (the first event's stream name) |
relay batch |
Internal | a relay run that claimed integration events (an empty claim is none) |
publish {EventName} |
Producer | each delivery; its parent is the trace the event was enqueued under, linked to its relay batch |
consume {EventName} {Consumer} |
Consumer | each inbox consumer the receiver runs; its parent is the envelope's trace context |
subscription {Name} poll |
Internal | a named subscription's poll that read events (an empty poll is none) |
| Instrument | Type | Tags |
|---|---|---|
xpandables.events.outbox.delivered, xpandables.events.outbox.failed, xpandables.events.outbox.parked |
counter ({event}) |
xpandables.event.name |
xpandables.events.inbox.completed, xpandables.events.inbox.duplicates, xpandables.events.inbox.suspended |
counter ({event}) |
xpandables.event.consumer |
xpandables.events.outbox.lag |
histogram (s), enqueue to delivery (a scheduled event's includes its wait) |
xpandables.event.name |
xpandables.events.outbox.rows |
observable gauge ({event}), counted by the relay at most every 30 s while observed |
xpandables.events.status = pending, parked |
A deferred delivery (a consumer whose inbox receipt is held elsewhere) is neither delivered nor failed: its spans end
without error and no outbox counter moves. A consumer registered with AddXEventConsumer (no inbox) has no consume
span.
The event and outbox tables keep the W3C traceparent and tracestate (columns TraceParent, TraceState) of the
activity current when the event was appended or enqueued; a tracestate wider than 256 characters is not kept (the
traceparent is). The relay hands the envelope on with its publish span's context, and the receiver parents its
consume spans with the envelope's: the request, the events it stored and the consumers that ran them later are one
trace, also across a broker that carries the envelope.
builder.Services.AddOpenTelemetry()
.WithTracing(tracing => tracing.AddSource("Xpandables.Events"))
.WithMetrics(metrics => metrics.AddMeter("Xpandables.Events"));
The failures of the relay, of the inbox consumers and of the subscriptions are logged in a scope carrying
CorrelationId, EventId and EventName.
π Native AOT
Xpandables.Events has no reflection-based discovery: nothing is scanned, the library closes no generic type at run time, and no member requires unreferenced or dynamic code.
- Consumers are registered by the generated
AddX{Assembly}EventConsumers()or by hand with the closed methods. AddXAggregateStore<TAggregate>()registers a closed store. The open genericAddXAggregateStore()andAddXAggregateStore(Type)leave the container to closeAggregateStore<>for each aggregate when it is resolved.- Event names, versions and aliases come from the generated
EventTypeRegistry(AddX{Assembly}CacheTypes()of each project); upcasters work on the JSON (Utf8JsonReader,Utf8JsonWriter,JsonNode). - The built-in entities (
DataEventDomain,DataEventSnapshot,DataEventInbox,DataEventOutbox) are[DataRecord]s, mapped by generated code. - Events and mementos are serialized through the registered
JsonSerializerContext. - Aggregates register their handlers with
On<TEvent>(Action<TEvent>).
Generated consumer registration
For an assembly that declares event consumers, Xpandables.Generators emits
System.Events.Generated.{Assembly}EventConsumerRegistrations.AddX{Assembly}EventConsumers(IServiceCollection), where
{Assembly} is the assembly name without its dots and other characters invalid in an identifier, each segment
capitalized (My.App and my.app give AddXMyAppEventConsumers). Each accessible,
non-abstract class implementing IEventConsumer<TEvent> is registered once per implemented interface: through
AddXIntegrationEventConsumer when TEvent is an integration event, else through
AddXEventConsumer. A generic consumer whose only type parameter is the event (AuditConsumer<TEvent> : IEventConsumer<TEvent>) is closed over every concrete, accessible event type of the assembly that satisfies its
constraints.
Diagnostics
| Id | Severity | Reported when |
|---|---|---|
XEC001 |
Warning | A consumer cannot be referenced by generated code (it or its event type is not accessible, it is nested in a generic type, or it or its event type is [Obsolete] as an error) and is not registered |
XEC002 |
Warning | An open-generic consumer matches no event of the assembly, or its type parameters are not just the event |
XCT001 |
Error | Two event types (or cache types) share a persisted name |
XCT002 |
Error | An [EventName]/[EventNameAlias]/[CacheType] name is empty |
XCT003 |
Error | An event name or alias resolves to two event types (an [EventNameAlias] repeats the name or an alias of another event) |
XCT004 |
Error | An [EventName] Version is below 1 |
XGN001 |
Warning | The generated registration class collides with one generated by a referenced assembly whose name maps to the same identifier |
π¦ Package Contents
| Namespace | Types |
|---|---|
System.Events |
IEvent, EventBase, EventNameAttribute, EventNameAliasAttribute, EventTypeInfo, EventTypeRegistry, UnknownEventTypeException, EventSerializer, SerializedEvent, IEventUpcaster, EventUpcastException, EventStatus, IEventPublisher, IEventPublisherExtensions, IEventSubscriber, IEventConsumer<T>, EventPublisherSubscriber, EventRegistryMode, IEventConsumerRegistry, StaticEventConsumerRegistry, DynamicEventConsumerRegistry, CompositeEventConsumerRegistry, IEventConsumerWrapper, EventConsumerWrapper<T>, HostedScheduler, EventStoreServiceKeys |
System.Events.DomainEvents |
IDomainEvent, DomainEvent, ISnapshotEvent, SnapshotEvent, IEventStore, IEventSourcing, IEventSourcingExtensions, IDomainEventEnricher, DefaultDomainEventEnricher, AppendRequest, AppendResult, EnvelopeResult, EventPosition, EventPositionJsonConverter, ReadStreamRequest, ReadAllStreamsRequest, SubscribeToStreamRequest, SubscribeToAllStreamsRequest, SubscriptionStartFrom, SubscriptionOptions, SubscriptionErrorPolicy, EventEnvelope, IEventSubscriptionStore, EventSubscriptionInfo, EventSubscriptionStatus, DeleteStreamRequest, TruncateStreamRequest, EventStreamConcurrencyException, EventStreamDeletedException, EventStreamCorruptedException, DomainEventMetaDataJsonStringConverter |
System.Events.Domain |
IAggregate, Aggregate, IAggregateFactory, IAggregateFactory<T>, CreateArgs, IAggregateStore, IAggregateStore<T>, AggregateStore<TAggregate>, AggregateStateContext<TState>, SnapshotOptions |
System.Events.IntegrationEvents |
IIntegrationEvent, IIntegrationEvent<T>, IntegrationEvent, IntegrationEvent<T>, IIntegrationEventEnricher, IntegrationEventEnricher, IEventBus, IntegrationEventEnvelope, IIntegrationEventReceiver, IntegrationEventReceiver, IOutboxStore, OutboxClaim, CompletedOutboxEvent, FailedOutboxEvent, DeferredOutboxEvent, ParkedOutboxEvent, IInboxStore, IInboxConsumer, InboxReceiveResult, SuspendedInboxEvent, CompletedInboxEvent, FailedInboxEvent, ReleasedInboxEvent, InboxOptions, InboxEventConsumerBehavior<TEvent, TConsumer>, InboxEventDeferredException, IPendingIntegrationEvents, PendingIntegrationEvents, IScheduler, IHostedScheduler, IEventSchedulerTrigger, EventSchedulerTrigger, SchedulerOptions, SchedulerBackoff, SchedulerHealthCheck, SchedulerHealthOptions, EventRetentionOptions, EventRetentionService, IRetentionPurge |
System.Events.Integration |
Scheduler |
System.Events.Data |
EventStore<TDomain, TSnapshot>, OutboxStore<T>, InboxStore<T>, IDataEvent, IDataEventDomain, IDataEventSnapshot, IDataEventOutbox, IDataEventInbox, DataEvent, DataEventDomain, DataEventSnapshot, DataEventOutbox, DataEventInbox, IEventConverter, IEventConverter<TDataEvent, TEvent>, JsonEventConverter<TDataEvent, TEvent>, EventConverterDomain, EventConverterSnapshot, EventConverterOutbox, EventConverterInbox, IEventConverterProvider, EventConverterProvider, EventConverterFactoryExtensions |
System.Events.Data.Scripts |
IEventTableScriptProvider, EventTableScriptProviders, SqlServerEventTableScripts, PostgreSqlEventTableScripts, SqliteEventTableScripts, EventTableScriptExporter |
Microsoft.Extensions.DependencyInjection |
IEventExtensions |
π License
Apache License 2.0 β see the LICENSE file for details.
<div align="center">
Built with β€οΈ using .NET 11
</div>
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Microsoft.Extensions.DependencyInjection (>= 11.0.0)
- Microsoft.Extensions.Diagnostics.HealthChecks (>= 11.0.0)
- Microsoft.Extensions.Hosting (>= 11.0.0)
- Xpandables.Data (>= 11.0.0)
- Xpandables.Generators (>= 11.0.0)
- Xpandables.Net (>= 11.0.0)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Xpandables.Events:
| Package | Downloads |
|---|---|
|
Xpandables.Events.Data
Events ADO.NET implementation. |
|
|
Xpandables.Results.Pipelines
Pipeline pattern implementation. |
|
|
Xpandables.AspNetCore.Net
ASP.NET Core minimal API integration of the Xpandables libraries: Result to HTTP responses and problem details, endpoint filters, routes, request context, pipeline behaviors and DI extensions; Native AOT compatible. |
|
|
Xpandables.Sagas
Distributed sagas over Xpandables.Events: orchestrated, observed and hybrid sagas, state machines, compensation, timeouts, retries, auditing and OpenTelemetry, on the transactional outbox and the idempotent inbox; Native AOT compatible. |
GitHub repositories
This package is not used by any popular GitHub repositories.