Repository navigation
Migrating from 0.x
This page covers every breaking change between the 0.x and 1.0 releases and shows what you need to change. Work through the sections in order; the checklist at the bottom summarises everything in one place.
The 0.x library was a monolith — one Aggregates package and one Aggregates.EventStoreDB package that contained everything. 1.0 decomposes it into focused packages, removes built-in serialisation, introduces an explicit subscription abstraction, and cleans up several inconsistencies in the public API.
The target framework moves from net8.0 to net10.0. Every project that references a 1.0 package must target net10.0, so upgrade the application to net10.0 first, as a separate step, while it still runs on 0.x: the 0.x packages work on net10.0 too.
<PackageReference Include="Aggregates" />
<PackageReference Include="Aggregates.EventStoreDB" />
<PackageReference Include="Aggregates.Json" /> <!-- or Aggregates.Protobuf -->
<PackageReference Include="Aggregates.Sql" /> <!-- if using SQL projections -->Add one core package, the storage integration you need, and separate add-on packages for whichever of sagas, policies and projections you use:
<!-- Core -->
<PackageReference Include="Aggregates" />
<!-- KurrentDB storage (rename of EventStoreDB) -->
<PackageReference Include="Aggregates.KurrentDB" />
<PackageReference Include="Aggregates.Sagas.KurrentDB" /> <!-- if using sagas -->
<PackageReference Include="Aggregates.Policies.KurrentDB" /> <!-- if using policies -->
<PackageReference Include="Aggregates.Projections.KurrentDB" /> <!-- if using projections -->
<PackageReference Include="Aggregates.KurrentDB.Migration" /> <!-- only for the switch-over, see §10 -->
<!-- Or MSSP storage -->
<PackageReference Include="Aggregates.MSSP" />
<PackageReference Include="Aggregates.Sagas.MSSP" />
<PackageReference Include="Aggregates.Policies.MSSP" />
<PackageReference Include="Aggregates.Projections.MSSP" />
<!-- SQL projections (renamed from Aggregates.Sql) -->
<PackageReference Include="Aggregates.Projections.Sql" />Aggregates.Json, Aggregates.Protobuf, and Aggregates.EventStoreDB no longer exist.
Most types keep their namespace. These moved:
| 0.x | 1.0 |
|---|---|
Aggregates.Metadata (MetadataAttribute, MetadataScope, MetadataMultiplicity) |
Aggregates |
Aggregates.Entities (EntityRoot) |
Aggregates |
Aggregates.Configuration (AggregatesOptions) |
Aggregates |
Aggregates (SagaCommitDelegate) |
Aggregates.Sagas |
Aggregates.Sql (IDbConnectionFactory, ISqlCommit, UseSql) |
Aggregates.Projections.Sql |
Aggregates.Sql.Extensions (ToTableValuedParameter) |
— (see SQL projections) |
Aggregates.EventStoreDB |
Aggregates.KurrentDB |
Aggregates.Metadata, Aggregates.Entities, Aggregates.Configuration and Aggregates.Sql no longer exist, so a using of one of them doesn't compile: remove it, or replace it with the namespace in the right-hand column.
0.x and 1.0 share the package id Aggregates and most namespaces, so one application references one of them, never both. See All hosts at once.
The old UseAggregates extension method is replaced by a fluent builder.
services.UseAggregates(options => {
options.Assemblies = [typeof(MyCommand).Assembly];
options.UseEventStoreDB("esdb://localhost:2113?tls=false");
options.UseJson();
// optional:
options.SagaKey = "Saga";
options.AggregateCreationBehaviour = AggregateCreationBehaviour.Automatic;
});// 1. Register the KurrentDB client yourself (any standard approach):
services.AddKurrentDBClient("kurrentdb://localhost:2113?tls=false");
// 2. Core aggregates + storage:
var registry = EventTypeRegistry.FromAssemblies(typeof(MyCommand).Assembly);
services.AddSingleton(registry); // event-type filter, see §10
var aggregates = services.AddAggregates(o => o.ScanAssemblies(typeof(MyCommand).Assembly));
aggregates.AddKurrentDb(o => {
o.Serialize = evt => new SerializedEvent(
registry.GetTypeName(evt),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null;
// metadata in the 0.x format, see Serialising metadata in §6:
o.SerializeMetadata = metadata => JsonSerializer.SerializeToUtf8Bytes(metadata);
o.DeserializeMetadata = JsonMetadata.Deserialize;
});
// 3. Add-ons (each has its own ScanAssemblies call):
aggregates.AddSagas(o => o.ScanAssemblies(typeof(MyCommand).Assembly)).AddKurrentDb();
aggregates.AddPolicies(o => o.ScanAssemblies(typeof(MyCommand).Assembly)).AddKurrentDb();
services.AddProjections(o => o.ScanAssemblies(typeof(MyCommand).Assembly)).AddKurrentDb();Key changes:
-
UseAggregates→AddAggregates. ReturnsIAggregatesBuilder, notIServiceCollection. -
UseEventStoreDB(connectionString)is removed. Register aKurrentDBClientyourself and call.AddKurrentDb(...). -
UseJson()/UseProtobuf()are removed. SupplySerializeandDeserializelambdas on the options object (see Serialisation below). - Metadata is stored only when
SerializeMetadatais set, and read only whenDeserializeMetadatais set (see Serialising metadata). -
SagaKeyis removed. Saga routing no longer uses metadata keys (see Sagas below). -
AggregateCreationBehaviouris removed. The singleCommandHandler<TCommand, TState, TEvent>always loads-or-creates.
The synchronous Progress method is removed. Implement only ProgressAsync.
record AddItem(AggregateIdentifier Id, string ItemId) : ICommand<Cart, ICartEvent> {
// could override either Progress or ProgressAsync
public IEnumerable<ICartEvent> Progress(Cart state) {
if (state.Contains(ItemId)) yield break;
yield return new ItemAdded(ItemId);
}
}record AddItem(AggregateIdentifier Id, string ItemId) : ICommand<Cart, ICartEvent> {
public async IAsyncEnumerable<ICartEvent> ProgressAsync(
Cart state,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
if (state.Contains(ItemId)) yield break;
yield return new ItemAdded(ItemId);
}
}The handler interface went from three type parameters to one.
class MyController(ICommandHandler<AddItem, Cart, ICartEvent> handler) { ... }class MyController(ICommandHandler<AddItem> handler) { ... }CancellationToken is now a parameter on HandleAsync:
await handler.HandleAsync(command);await handler.HandleAsync(command, cancellationToken);When you need to dispatch a command whose concrete type is only known at runtime (common in sagas and policies), use ICommandDispatcher:
await dispatcher.DispatchAsync(command, cancellationToken);Register it with AddAggregates — it is included automatically.
The marker-interface-based creation mode (AggregateCreationBehaviour.UseMarkerInterface<ICreateCommand>()) is removed. All commands now use the single load-or-create strategy. If you distinguished creation commands with a marker interface, remove that distinction — the behaviour is now identical.
0.x retried an append that failed with an RpcException (DeadlineExceeded or Unknown), four attempts in all, and after the last one it returned as if the commit had succeeded. 1.0 doesn't retry the append: the exception reaches the caller of HandleAsync. What 1.0 retries, and 0.x didn't, is a ConcurrencyException: the decorator chain loads the aggregate again and runs the command, up to three attempts in all.
A command that a saga or policy dispatches is covered by its subscription: a failed reaction is retried with backoff, then parked or blocked (see Policies). For commands sent from an API or a job, add your own retry where you relied on the one in 0.x.
EntityCommitDelegate is renamed to CommitDelegate, and both CommitDelegate and SagaCommitDelegate take a CancellationToken as their second parameter: (unitOfWork, cancellationToken). SagaCommitDelegate moved to Aggregates.Sagas. The storage integration registers both; this only matters if you register your own, for example a fake in tests. Pass the token to the append. See API Reference.
Built-in serialisation packages (Aggregates.Json, Aggregates.Protobuf) are removed. You supply two lambdas on the storage integration options.
options.UseJson(); // registered SerializerDelegate / DeserializerDelegateUse EventTypeRegistry (included in the Aggregates core package) to translate between CLR types and the stable event names stored in the event store. Build it once at startup:
var registry = EventTypeRegistry.FromAssemblies(typeof(OrderPlaced).Assembly);Then pass it to the storage integration options (KurrentDB example; MSSP is identical in shape):
.AddKurrentDb(o => {
o.Serialize = evt => new SerializedEvent(
registry.GetTypeName(evt.GetType()),
JsonSerializer.SerializeToUtf8Bytes(evt, evt.GetType()));
o.Deserialize = (typeName, data) =>
registry.TryGetType(typeName, out var clrType)
? JsonSerializer.Deserialize(data.Span, clrType)
: null; // unknown type name → skip
});EventTypeRegistry.FromAssemblies scans the given assemblies for types decorated with [EventContract] and builds a bidirectional name ↔ CLR type map. Pass all assemblies that contain event records — including historical versions you need to be able to deserialise. GetTypeName falls back to the full CLR type name (Orders.Events.ItemAdded) for undecorated types, where 0.x stored the short name (ItemAdded); 0.x never read such events back, so put [EventContract] on every event. The opt-in package Aggregates.Analyzers reports every event without it as a build warning (AGG0001); see Aggregates.Analyzers. TryGetType returns false for unknown names, so the null from Deserialize signals the infrastructure to skip that event.
Use the same JsonSerializerOptions as 0.x: the ones you passed to UseJson(options), or the defaults (as above) when you called UseJson() without arguments. Your Deserialize reads the events 0.x wrote, and 0.x wrote their metadata with the same options (see Serialising metadata).
EventContractAttribute itself is unchanged, and so are upgraders: the eventUpgrader sits on the old version, and the storage integration applies the chain after your Deserialize, as 0.x did after its deserializer. You don't upgrade in Deserialize yourself; if you already do, it's harmless, because the last version has no upgrader. EventTypeRegistry reuses the same attribute to produce its mappings.
New in 1.0: building the EventTypeRegistry checks every upgrader. It must implement IUpgradeEvent<TOld, TNew> exactly once, with TOld the type it sits on. 0.x only showed such a mistake when it read an event of that type (an ArgumentException from the upgrader); 1.0 fails at startup and lists every misconfigured upgrader. Fix them before you switch over. Typical cause: an upgrader on the new version instead of the old one, e.g. V4 with eventUpgrader: typeof(V3ToV4) where V4ToV5 was meant. The registry doesn't check whether every old version has an upgrader.
1.0 also refuses at startup two types with the same [EventContract] name, and a contract (event, projection, policy or saga) with an empty name or a version below 1; 0.x accepted version: 0. Loading an aggregate or saga fails on a stream that doesn't start at revision 0 or has a gap ($tb or $maxCount on the stream, or a soft-deleted stream written again), where 0.x loaded it and then failed every commit on the expected version. As in 0.x, loading also fails on an event that Deserialize doesn't know or that isn't a TEvent, so keep every stored event version in your code and in the registry.
Also register the registry in the container (services.AddSingleton(registry)), so that subscriptions filter on event type in the store as the 0.x persistent subscription groups did. See Event-type filter.
Event ids on KurrentDB are still deterministic (an MD5 hash of the stream name, the position, an XxHash64 of the data and the stored event type), but the input changed, so 1.0 gives a change another id than 0.x did. That only matters if something relies on KurrentDB's idempotent append across the two versions.
The generic MetadataAttribute<TContext> / MetadataAttribute<TContext, TValueProvider> variants and the IMetadataProvider<TContext> interface are removed. Subclass the base attribute directly.
sealed class CorrelationIdAttribute()
: MetadataAttribute<AddItem>("correlationId") { }
// AddItem : IMetadataProvider<AddItem>
record AddItem(...) : ICommand<...>, IMetadataProvider<AddItem> {
public object? GetValue(string key, AddItem context) => context.CorrelationId;
}sealed class CorrelationIdAttribute() : MetadataAttribute("correlationId") {
public override ValueTask<object?> GetValueAsync(object context, CancellationToken ct) =>
ValueTask.FromResult<object?>(((AddItem)context).CorrelationId);
}
[CorrelationId]
record AddItem(...) : ICommand<...> { ... }Note: in 1.0, MetadataAttribute may only be applied to state and command types. Applying it to event classes has no effect.
Current is now nullable. In 0.x it always returned a scope (returning an inert no-op scope when none was active). In 1.0 it returns null when no scope is active.
MetadataScope.Current.Add("key", value); // always safe
var dict = MetadataScope.Current.ToDictionary();MetadataScope.Current?.Add("key", value); // null-conditional required
var snapshot = MetadataScope.Current?.Snapshot(); // returns EventMetadata or nullToDictionary() is replaced by Snapshot(), which returns an immutable EventMetadata (IReadOnlyDictionary<string, object?>).
MetadataScope is only IAsyncDisposable now; 0.x was also IDisposable. A scope you open yourself needs await using:
await using var scope = new MetadataScope();As in 0.x, a scope opened inside another one starts with a copy of its entries, and its own additions don't reach the outer scope. new MetadataScope(EventMetadata.Empty) opens an empty one.
MetadataAttribute, MetadataScope and MetadataMultiplicity moved from Aggregates.Metadata to Aggregates (see Namespaces).
0.x always stored the metadata scope with each event, as a JSON object written with the event serializer. 1.0 stores metadata only when SerializeMetadata is set, and reads it only when DeserializeMetadata is set. Without DeserializeMetadata, every handler sees EventMetadata.Empty, and a saga can't read the Saga key of the events 0.x committed (see Saga streams).
To keep the 0.x format, write the metadata as a JSON object with the options 0.x used, and read a stored object back with nested objects as dictionaries and arrays as object?[]:
o.SerializeMetadata = metadata => JsonSerializer.SerializeToUtf8Bytes(metadata);
o.DeserializeMetadata = JsonMetadata.Deserialize;static class JsonMetadata {
public static EventMetadata Deserialize(ReadOnlyMemory<byte> data) {
using var document = JsonDocument.Parse(data);
return document.RootElement.ValueKind == JsonValueKind.Object
? new EventMetadata(document.RootElement.EnumerateObject()
.Select(property => KeyValuePair.Create(property.Name, ToValue(property.Value))))
: EventMetadata.Empty;
}
static object? ToValue(JsonElement element) => element.ValueKind switch {
JsonValueKind.Object => element.EnumerateObject()
.ToDictionary(property => property.Name, property => ToValue(property.Value)),
JsonValueKind.Array => element.EnumerateArray().Select(ToValue).ToArray(),
JsonValueKind.String => element.GetString(),
JsonValueKind.Number when element.TryGetInt64(out var integer) => integer,
JsonValueKind.Number => element.GetDouble(),
JsonValueKind.True => true,
JsonValueKind.False => false,
_ => null,
};
}An event stored without metadata never reaches DeserializeMetadata: it gets EventMetadata.Empty.
Values as JsonElement. 0.x read the metadata as a Dictionary<string, object?> with the options of the event serializer, so every value was a JsonElement. JsonMetadata above gives string, long, double, bool, dictionaries and object?[] instead, and code that casts a value to JsonElement fails on it. To keep the 0.x values exactly, read them the way 0.x did:
o.DeserializeMetadata = data =>
JsonSerializer.Deserialize<Dictionary<string, object?>>(data.Span, options) is { } values
? new EventMetadata(values)
: EventMetadata.Empty;Choose JsonElement values to keep existing code that reads metadata unchanged; choose JsonMetadata for new code, for Correlate, and wherever a key with MetadataMultiplicity.Multiple is added to further: a saga or policy starts its scope from the event's metadata, and with JsonElement values an array there is one value, so a further Multiple addition nests it ([[a, b], c]) instead of appending ([a, b, c]). 0.x unfolded such an array from 0.54.1 on; events written before keep the nested arrays.
Keys with MetadataMultiplicity.Multiple. 0.x stored a key with a single value as that value, 1.0 as an array of one ("a" versus ["a"]). Code that reads such a key accepts both.
Keys passed on. The scope of a saga or policy starts with every key of the event it handles, so the commands it dispatches store those keys again. That includes the Saga key of the events 0.x committed: the events that follow from such an event in 1.0 carry it too. 1.0 never reads it, but 0.x does, after a rollback, and so does a Correlate that reads it (see Saga streams): take only the value of the event's own type, and expect nested arrays in events written before 0.54.1.
Sagas change from a delegate-method discovery model to an interface model.
A [SagaContract]-attributed class with arbitrary method(s) matching SagaAsyncDelegate<...>:
[SagaContract("OrderFulfillment")]
class OrderFulfillmentSaga {
public async IAsyncEnumerable<ShipOrder> OnOrderPlaced(
OrderFulfillmentState state,
OrderPlaced @event,
IReadOnlyDictionary<string, object?>? metadata = null,
CancellationToken cancellationToken = default) {
yield return new ShipOrder(@event.OrderId);
}
}A class implementing ISaga<TSagaState, TEvent> once:
[SagaContract("OrderFulfillment")]
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, OrderPlaced> {
public IEnumerable<AggregateIdentifier> Correlate(OrderPlaced @event, EventMetadata metadata) =>
[new AggregateIdentifier($"order-fulfillment-{@event.OrderId}")]; // see Routing below
public async IAsyncEnumerable<ICommand> ReactAsync(
OrderFulfillmentState state,
OrderPlaced @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
yield return new ShipOrder(@event.OrderId);
}
}A saga that reacts to several event types uses a marker interface as TEvent, and pattern matching in ReactAsync and in the state's Apply. Each 0.x saga method becomes one case:
interface IOrderFulfillmentEvent { string OrderId { get; } } // implemented by OrderPlaced and OrderPaid
[SagaContract("OrderFulfillment")]
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, IOrderFulfillmentEvent> {
public IEnumerable<AggregateIdentifier> Correlate(IOrderFulfillmentEvent @event, EventMetadata metadata) =>
[new AggregateIdentifier($"order-fulfillment-{@event.OrderId}")];
public async IAsyncEnumerable<ICommand> ReactAsync(
OrderFulfillmentState state,
IOrderFulfillmentEvent @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
switch (@event) {
case OrderPlaced placed:
yield return new ShipOrder(placed.OrderId);
break;
case OrderPaid paid when state.IsShipped:
yield return new CloseOrder(paid.OrderId);
break;
}
}
}Don't implement ISaga<,> more than once on a class: registration fails. The saga state is rebuilt from the events of its TEvent only, so a saga with a second interface would see half of its own history.
The 0.x metadata parameter is gone. Correlate gets the event's metadata as a parameter; during ReactAsync, MetadataScope.Current holds it (see Reading the event's metadata).
In 0.x, saga routing was driven by metadata: a [Saga<TEvent, TIdProvider>] attribute on the event class wrote the saga ID into the event's metadata under the configured SagaKey. The saga worker then read that key back.
This mechanism is completely removed. In 1.0 each saga routes events itself, with Correlate on ISaga<TSagaState, TEvent>: it returns the ids of the saga instances that react to an event. There is nothing to register; every scanned saga is subscribed.
// On the event class:
[Saga<OrderPlaced, OrderIdProvider>("Saga")]
record OrderPlaced(string OrderId, ...);
class OrderIdProvider : ISagaIdProvider<OrderPlaced> {
public AggregateIdentifier GetSagaId(OrderPlaced @event) => new(@event.OrderId);
}// On the event class: nothing
record OrderPlaced(string OrderId, ...);
// On the saga:
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, IOrderFulfillmentEvent> {
public IEnumerable<AggregateIdentifier> Correlate(IOrderFulfillmentEvent @event, EventMetadata metadata) =>
metadata.TryGetValue("OrderFulfillmentId", out var value) && value is object?[] ids
? ids.OfType<string>().Select(id => new AggregateIdentifier(id))
: [];
// ReactAsync as above
}Correlate receives both the event and its stored metadata. Reading a metadata key is the natural migration path from 0.x: in 0.x the library wrote saga identifiers to a metadata key automatically; in 1.0 you write them yourself (via MetadataScope.Current?.Add("OrderFulfillmentId", sagaId, MetadataMultiplicity.Multiple) in a command or state attribute) and read them back in Correlate. When the saga id is a property on the event body, return it directly: [new AggregateIdentifier($"order-fulfillment-{@event.OrderId}")].
The saga identifier is also the name of the saga's stream, so two sagas that return the same identifier share a stream and read each other's events. Give each saga its own prefix, or, with the metadata route, its own metadata key. To share the routing logic between sagas, call a helper of your own from each Correlate.
Correlate runs once per event on a saga from a fresh DI scope, so it can use the saga's dependencies. Derive the ids from the event and its metadata only: a redelivered or replayed event must reach the same instances.
The stream format is unchanged from 0.x: a saga stream holds link events (type $>, data "{revision}@{stream}"), one per event the saga handled, never copies of those events. Saga streams written by 0.x are read without conversion, and new entries are links too, so an in-flight 0.x saga simply continues.
To pick up an in-flight 0.x saga, its 1.0 Correlate must return exactly the 0.x saga id: the value ISagaIdProvider<TEvent>.GetSagaId returned. The saga id is the stream name, literally; 1.0 adds no prefix.
Events committed by 0.x still carry the saga id in their metadata, under the key Saga (or the key configured in AggregatesOptions.SagaKey): one object { "EventType": "<assembly-qualified name of the reaction event>", "SagaId": "…" }, or an array of them. Correlate can read that key for events from before the cutover, and use its own mechanism (an event property, or a key you write via MetadataScope) for new events. The shape Correlate sees depends on your DeserializeMetadata; with a JSON deserializer that yields dictionaries and arrays, it looks like this:
public IEnumerable<AggregateIdentifier> Correlate(IOrderFulfillmentEvent @event, EventMetadata metadata) =>
metadata.TryGetValue("Saga", out var value)
? ZeroXSagaIds(value) // event committed by 0.x
: [new AggregateIdentifier(@event.OrderId)]; // event committed by 1.0
static IEnumerable<AggregateIdentifier> ZeroXSagaIds(object? value) =>
(value is object?[] array ? array : [value])
.OfType<IReadOnlyDictionary<string, object?>>()
.Where(saga => saga.TryGetValue("EventType", out var type) && type is string name && name.StartsWith("MyApp.OrderPlaced,"))
.Select(saga => new AggregateIdentifier((string)saga["SagaId"]!));EventType and SagaId are the names under the default JsonSerializerOptions. With a PropertyNamingPolicy in the options 0.x used, they are named after that policy (for example eventType and sagaId).
Things to know:
- One reaction per event. A saga reacts at most once to a given stored event: before reacting, it checks whether its stream already links to that event. A redelivery (for example after a crash between the saga commit and the checkpoint) does nothing.
-
Only links. A saga stream that holds anything but links is rejected: the event is parked with "Stream '…' is not a saga stream". That catches a
Correlatethat returns an aggregate id. -
Unique stream names. Two sagas that return the same id from
Correlateshare a stream and see each other's links, so the second one never reacts. Give every saga its own prefix ($"order-fulfillment-{@event.OrderId}"); for 0.x sagas, keep the 0.x id. -
Retention. A link to a deleted or scavenged event cannot be resolved: it still counts for the saga's version, but the saga's state misses that event, as in 0.x.
$maxAgeor$tbon aggregate streams therefore affects the sagas that link to them. - Semantics. As in 0.x: the saga reacts with the state before the event, and its state after rehydration is the same.
| Removed | Replacement |
|---|---|
SagaAttribute<TEvent, TIdProvider> |
ISaga<TSagaState, TEvent>.Correlate on each saga |
ISagaIdProvider<TEvent> |
ISaga<TSagaState, TEvent>.Correlate |
SagaDelegate / SagaAsyncDelegate
|
ISaga<TSagaState, TEvent>.ReactAsync |
SagaMetadata |
— (1.0 no longer writes it; read it from events committed by 0.x, see Saga streams) |
AggregatesOptions.SagaKey |
— |
Saga methods on IRepository<,>
|
ISagaRepository<TSagaState, TEvent> (registered by storage package) |
Policies follow the same delegate-to-interface change as sagas.
[PolicyContract("SendWelcomeEmail")]
class SendWelcomeEmailPolicy {
public async IAsyncEnumerable<SendEmail> OnUserRegistered(
UserRegistered @event,
IReadOnlyDictionary<string, object?>? metadata = null,
CancellationToken cancellationToken = default) {
yield return new SendEmail(@event.Email, "Welcome!");
}
}[PolicyContract("SendWelcomeEmail")]
class SendWelcomeEmailPolicy : IPolicy<UserRegistered> {
public async IAsyncEnumerable<ICommand> ReactAsync(
UserRegistered @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
yield return new SendEmail(@event.Email, "Welcome!");
}
}A policy class implements IPolicy<TEvent> once; registration fails otherwise. To react to several event types, use a marker interface (or object) as TEvent and pattern matching in ReactAsync, with one case per 0.x method.
0.x collected the whole reaction before it dispatched a command. 1.0 dispatches each command as soon as the policy yields it, and a retry runs the whole reaction again. When ReactAsync throws halfway, for example in a query between two yields, the commands yielded before the exception have run, and the retry runs them again.
// 1.0: SendInvoice has run when the query throws, and runs again on the retry
yield return new SendInvoice(@event.OrderId);
var customer = await customers.GetAsync(@event.CustomerId, cancellationToken);
yield return new NotifyCustomer(customer.Email);Where that matters, collect the commands first and yield them afterwards, in the policy that needs it:
var customer = await customers.GetAsync(@event.CustomerId, cancellationToken);
ICommand[] commands = [new SendInvoice(@event.OrderId), new NotifyCustomer(customer.Email)];
foreach (var command in commands)
yield return command;There is no option for this. Sagas dispatched per yield in 0.x already.
0.x passed the event's metadata as a parameter; ReactAsync has none. During the reaction, MetadataScope.Current holds the event's metadata, and the commands the policy dispatches inherit it, as in 0.x:
public async IAsyncEnumerable<ICommand> ReactAsync(
UserRegistered @event,
[EnumeratorCancellation] CancellationToken cancellationToken = default) {
var metadata = MetadataScope.Current?.Snapshot() ?? EventMetadata.Empty;
if (metadata.TryGetValue("tenant", out var tenant) && tenant is string name)
yield return new SendEmail(@event.Email, $"Welcome to {name}!");
}A saga's ReactAsync works the same way.
The errorHandlingMode, maxErrors and maxErrorRate parameters are removed. continueFrom and startFromEnd remain; see Contract versions.
[PolicyContract("SendWelcomeEmail", errorHandlingMode: PolicyErrorHandlingMode.ContinueOnError)][PolicyContract("SendWelcomeEmail")]Error handling is now handled automatically at the subscription infrastructure level rather than per-contract. All subscription services (sagas, policies, projections) retry failed handlers with exponential backoff and park messages that still fail after all attempts, allowing the subscription to continue. 0.x parked too, after five retries by the server; 1.0 retries in the host, with backoff, before it parks. See Subscription error handling for configuration options.
The 0.x modes were about the commands one reaction returned (stop at the first that failed, continue, or continue up to a threshold); 1.0 has no such modes: when one command fails, the whole reaction is retried. The commands before the failing one are then dispatched again, so they must be idempotent. 0.x ContinueOnError acknowledged the event instead, and the failed command was lost. What a contract can choose is what happens to an event that still fails: park it (the default) or block until it succeeds (onError: SubscriptionErrorMode.Block). See Parked messages.
[ProjectionContract("OrderSummary")]
class OrderSummaryProjection(IDbConnectionFactory db) {
public ICommit OnOrderPlaced(OrderPlaced @event, IReadOnlyDictionary<string, object?>? metadata = null) =>
Commit.Create().UseSql(db).Query("INSERT INTO OrderSummary (OrderId) VALUES (@OrderId)", new { @event.OrderId });
}[ProjectionContract("OrderSummary")]
class OrderSummaryProjection(IDbConnectionFactory db) : IProjection<OrderPlaced> {
public ValueTask<ICommit> ProjectAsync(
OrderPlaced @event,
EventMetadata metadata,
CancellationToken cancellationToken = default) =>
ValueTask.FromResult<ICommit>(
Commit.Create().UseSql(db).Query("INSERT INTO OrderSummary (OrderId) VALUES (@OrderId)", new { @event.OrderId }));
}The untyped IReadOnlyDictionary<string, object?>? metadata parameter from 0.x delegates is replaced by the strongly-typed EventMetadata metadata parameter on ProjectAsync.
continueFrom and startFromEnd remain; see Contract versions.
A projection class implements IProjection<TEvent> once; registration fails otherwise. To handle several event types, use a marker interface (or object) as TEvent and pattern matching in ProjectAsync, with one case per 0.x method. The events then arrive in the order they were stored. Several projection classes may handle the same event type.
The package is renamed from Aggregates.Sql to Aggregates.Projections.Sql, and so is the namespace. UseSql(factory, isolationLevel) and Query(sql, parameters, commandType) work as in 0.x, with these differences:
| 0.x | 1.0 | |
|---|---|---|
IDbConnectionFactory |
DbConnection CreateConnection() |
ValueTask<DbConnection> CreateAsync(CancellationToken cancellationToken = default) |
Default isolation level of UseSql
|
IsolationLevel.Unspecified, the provider's default |
IsolationLevel.ReadCommitted; pass IsolationLevel.Unspecified to keep the 0.x behaviour |
A null parameter value |
sent as null, which SqlClient rejects as a missing parameter |
sent as DBNull.Value
|
ToTableValuedParameter |
IEnumerable<T> → DataTable, in Aggregates.Sql.Extensions
|
removed; copy the 0.x helper into your application if you use it |
| ADO.NET provider | not included: the application adds its package | the same |
New in 1.0: RecordSqlPositions runs the statements of a UseSql transaction once per event, also when the event is delivered again (SQL Server only). It replaces hand-made deduplication of SQL writes. See RecordSqlPositions.
In 0.x, subscription state was managed by EventStoreDB's server-side persistent subscriptions. In 1.0 the library owns checkpoint persistence via ICheckpointStore.
You do not implement anything here — the storage integration packages (*.KurrentDB, *.MSSP) register concrete ICheckpointStore and ISubscriptionFactory implementations automatically. The hosted services that drive sagas, policies, and projections are also registered automatically by AddSagas/AddPolicies/AddProjections.
Existing persistent subscription state is not migrated by itself. Import it once with Aggregates.KurrentDB.Migration before the first 1.0 host starts; see Importing 0.x subscription positions. Without an import, each subscription starts from the beginning, or from the end with startFromEnd. After the import, each subscription starts from the position stored in its checkpoint stream, or in that of an older contract version (see Contract versions).
Each projection, policy and saga class is one subscription, as each contract was one persistent subscription group in 0.x. The subscription id is the same string as the 0.x group name: the contract's {namespace}.{name}@v{version}. Contracts must be unique across projections, policies and sagas; two classes with the same contract fail at registration. See One subscription per handler class.
Like the 0.x workers, the subscriptions survive connection loss and server restarts: they subscribe again with backoff and log every attempt. Unlike 0.x, this covers every transient failure, not only RpcException; only failures that need a configuration change (permissions, credentials) stop the subscription. See Resubscribing.
An event that Deserialize throws on is parked per subscription, and the subscription continues. Return null from Deserialize for event types you don't know instead of throwing: null skips the event without parking it. See Unknown event types.
continueFrom works as in 0.x on all three contracts, with a wider default: a new contract version continues where an older version stopped instead of replaying history.
| 0.x | 1.0 | |
|---|---|---|
Default predecessor of @v3
|
@v2 only |
@v2, then @v1: the nearest one with a checkpoint |
| Bump by more than one | replays (when @v2 never ran) |
continues from the nearest older version |
| Replay on purpose | bump by more than one |
continueFrom: ContinueFrom.None ("") |
| Old subscription | persistent subscription group deleted | checkpoint kept (rollback stays possible) |
| Position source | the group's LastKnownEventPosition (null after a cluster restart, which replayed) |
the old version's checkpoint stream |
A new version writes the adopted checkpoint as its own before it subscribes, and logs a warning when it skips a version or finds no predecessor checkpoint at all (then it starts from the beginning, or the end with startFromEnd). Two versions of one contract in the same host fail at registration. Stop the old version before starting the new one: unlike 0.x, which deleted the old group, a new version cannot stop an old one running in another host. See Where a subscription starts.
If you replayed by bumping the version by two, use continueFrom: ContinueFrom.None instead.
Switch over all hosts of an environment at once, following the switch-over in Importing 0.x subscription positions. 0.x and 1.0 share the package id Aggregates, so one process holds one of them, and running 0.x hosts next to 1.0 hosts on the same store is not supported. For example, 1.0 never writes the Saga metadata key, so a 0.x saga would silently stop reacting to the events a 1.0 host commits.
0.x kept each subscription's position in a persistent subscription group on the server; 1.0 keeps it in checkpoint-{id}. The package Aggregates.KurrentDB.Migration writes each group's position as the first checkpoint of the 1.0 subscription with the same id, so the switch-over neither replays history nor skips events. The group name is the subscription id ({namespace}.{name}@v{version}); when 1.0 runs a higher contract version, it continues from the imported checkpoint (see Contract versions). 0.x only ran on EventStoreDB/KurrentDB, so this is KurrentDB only.
PersistentSubscriptionMigration has two methods. PlanAsync is the dry-run: it reads the groups and the checkpoints, writes nothing, and returns a plan whose ToString() is a report with one row per group and per 1.0 subscription. ApplyAsync executes a plan; it refuses while any group is blocked, and when the store changed since the plan was made. Run it from a small console that registers the hosts' handlers without starting a host, so the plan can show where every 1.0 subscription starts:
var services = new ServiceCollection();
services.AddKurrentDBClient(connectionString);
var aggregates = services.AddAggregates(o => o.ScanAssemblies(typeof(PlaceOrder).Assembly));
aggregates.AddKurrentDb(o => { o.Serialize = …; o.Deserialize = …; });
services.AddProjections(o => o.ScanAssemblies(typeof(OrderSummary).Assembly)).AddKurrentDb();
aggregates.AddPolicies(o => o.ScanAssemblies(typeof(ShippingPolicy).Assembly)).AddKurrentDb();
aggregates.AddSagas(o => o.ScanAssemblies(typeof(FulfillmentSaga).Assembly)).AddKurrentDb();
await using var provider = services.BuildServiceProvider(); // no host: no subscription runs
var migration = new PersistentSubscriptionMigration(
provider.GetRequiredService<KurrentDBClient>(),
new KurrentDBPersistentSubscriptionsClient(KurrentDBClientSettings.Create(connectionString)));
var options = new MigrationOptions {
Registrations = [.. provider.GetServices<SubscriptionRegistration>()],
EventTypeRegistry = registry,
};
var plan = await migration.PlanAsync(MigrationStep.Import, options);
Console.WriteLine(plan);
if (args.Contains("--apply"))
Console.WriteLine(await migration.ApplyAsync(plan));What the import does with a group depends on its state:
| State | Meaning | Import |
|---|---|---|
Exact |
Drained: no consumer connected, nothing waiting to be delivered, redelivered or acknowledged. Every event the group read was acknowledged. | Writes the position of the last event read. |
AtLeastOnce |
Not drained: events are unread, or were delivered without their acknowledgement reaching the server. | Blocked, unless AllowAtLeastOnce: then imported at the group's own checkpoint, so events after it that 0.x already handled are handled again. |
Unknown |
Not drained and no checkpoint. | Blocked. |
Empty |
The group read nothing. | Nothing: the 1.0 subscription starts as its contract says. |
Connected |
A 0.x consumer is connected; the reason says whether it has caught up. | Blocked. |
An existing checkpoint-{id} at the same position means the group was imported already (repeating the import is safe); at another position it is kept, because a 1.0 subscription probably ran already, unless Overwrite is set.
Why not LastKnownEventPosition. It is the last event the server read for the group, including events it buffered while no consumer was connected, and it is null after a server restart. Importing it as such would skip events. The import only uses it when the group is drained; otherwise it falls back to the group's own checkpoint (LastCheckpointedEventPosition), which survives a restart but lags a few events behind.
The switch-over.
- Before the switch-over, run the dry-run against each environment while 0.x still runs, and resolve every warning in the subscription table: a 1.0 subscription that starts from the beginning means a renamed contract, another namespace, a class without contract, or a lower version than 0.x ran (set
continueFromto the 0.x name). A difference in event types means the 1.0 handler receives types the 0.x group did not (or the other way round), from the import on;all (0.x: n)is a handler ofobjectwhose 0.x group read only n types (see Event-type filter). The subscriptions that start from the beginning or the end on purpose (a new 1.0 handler, anEmptygroup) go inSubscriptionCheckpointOptions.AllowedWithoutCheckpointfor the 1.0 hosts, withRequireCheckpoint = true(see step 6). - Stop the writers: everything that sends commands (API, UI, scheduled jobs). Keep the 0.x hosts with projections, policies and sagas running.
- Run the dry-run until every group is
Connectedand "caught up", twice in a row: policies and sagas cause new events that must be handled too. - Wait a few seconds (at least 3), then stop the 0.x hosts. A 0.x consumer that stops right after an acknowledgement can lose it, which leaves the group not drained.
- Run the dry-run: every group should be
Exact. For a group that isn't, start its 0.x host again and repeat steps 3–4, or accept duplicates withAllowAtLeastOncefor groups without side effects. - Apply the plan, then start the 1.0 hosts. A 1.0 host that starts before the import replays from the beginning (or the end) and writes its own checkpoint, so the order matters. Start the 1.0 hosts with
SubscriptionCheckpointOptions.RequireCheckpoint = trueto enforce it: a host that starts too early then stops before it handles or writes anything, and the import still works. See Where a subscription starts. - Open the writers again.
Cleaning up and rolling back.
-
MigrationStep.Deletedeletes the groups that were imported. It refuses a group without a 1.0 checkpoint, and a group with parked messages unlessDiscardParkedMessages: deleting a group deletes its parked messages, which 1.0 can't take over. Replay them in 0.x first (ReplayParkedMessagesToAllAsync). -
MigrationStep.Rollbackcreates a group that still exists again, with its own settings and event-type filter, starting at the first event after the 1.0 checkpoint, so 0.x continues where 1.0 stopped. Pass the registrations when 1.0 runs a higher version than the group, so the rollback uses the checkpoint of the version that ran. Stop the 1.0 hosts first; a rollback doesn't undo what 1.0 did in the meantime. - Delete therefore closes the rollback window: delete the groups only once 1.0 is accepted.
Selecting groups. IncludeGroup selects groups by name. With registrations, OnlyRegistered selects only the groups named after a registered subscription or one of its predecessors, and leaves the other groups alone.
Permissions. Listing the groups needs $ops or $admins. The event-type filters are read from $persistentSubscriptionConfig, which needs $admins; without it, the import and the deletion work, but the rollback and the event-type comparison don't.
0.x created each persistent subscription group with a server-side EventTypeFilter.RegularExpression of the [EventContract] names its handler accepted, so a group only read its own event types. 1.0 does the same once an EventTypeRegistry is registered in the container; without one, every subscription reads and deserialises every event in the store.
| 0.x | 1.0 | |
|---|---|---|
| Turned on | always | when an EventTypeRegistry is registered in the container |
| Names from | the [EventContract] types assignable to the handler's event type that passed a trial when the group was created: an instance made with the parameterless constructor was given to the handler (a saga: to the Apply of its state); a type whose trial threw, or that had no parameterless constructor, was left out |
EventTypeRegistry.GetTypeNames: every type assignable to the handler's event type, including older versions with an upgrader to an accepted type |
| Fixed | when the group is created; a change needs a new contract version | computed again at every start; a change needs no version bump |
Handler of object
|
the same trial, over every [EventContract] type |
not filtered |
A handler whose 0.x method threw on the events it didn't want (a default arm with throw, or a cast) used that trial as its filter. In 1.0 it receives those types too: they fail, are retried and parked, or block the subscription with SubscriptionErrorMode.Block. Give each such handler a marker interface on exactly the types its 0.x group read, and use it as TEvent. The dry-run of the import lists the difference per subscription in EventTypes (+A, or all (0.x: n) for a handler of object; see Importing 0.x subscription positions).
| Quiet subscription | the group's position moves on in the server | the checkpoint is written once per MaxFilteredEvents skipped events (KurrentDB) |
Because the filter is no longer fixed in a group, a contract version bump now only decides where a subscription starts and under which id its checkpoint is kept. Adding an event type to a handler's marker interface takes effect at the next start, from the checkpoint, without replaying that type's history; to replay, bump the version with continueFrom: ContinueFrom.None.
Serialize must store events under the registry's names: a subscription filters on those names and never sees an event stored under another one. The commit handler logs a warning once per type when the names differ. See Event-type filter.
| 0.x | 1.0 | |
|---|---|---|
| Where | in the persistent subscription group, on the server |
parked-{subscription id} in the store, as $aggregates-parked events |
| Replay | the server's tools (ReplayParkedMessagesToAllAsync, the admin UI) |
IParkedMessages in the host: list, replay, replay all, dismiss |
| After a version bump | the old group's messages stay with the old group | the new version replays the messages of the old one |
| To keep the order | — |
onError: SubscriptionErrorMode.Block on the contract: never park, retry until it succeeds |
1.0 doesn't import the parked messages of a 0.x group. Replay them in 0.x before the switch-over, or decide to drop them; MigrationStep.Delete refuses a group that still holds parked messages unless DiscardParkedMessages (see Importing 0.x subscription positions). See Replaying parked messages.
| # | What to change |
|---|---|
| 1 | Replace Aggregates.EventStoreDB, Aggregates.Json, Aggregates.Protobuf, Aggregates.Sql references with the new per-concern packages. Bump TFM to net10.0. Upgrade the application to net10.0 first, still on 0.x. Fix the moved namespaces and remove the usings of the ones that are gone (see Namespaces). |
| 2 | Replace UseAggregates(opts => opts.UseEventStoreDB(...).UseJson()) with the fluent AddAggregates(...).AddKurrentDb(o => { o.Serialize=...; o.Deserialize=...; }) chain. Register KurrentDBClient separately. |
| 3 | Build an EventTypeRegistry with EventTypeRegistry.FromAssemblies(...) and use it in your Serialize / Deserialize lambdas. Pass all assemblies that contain event records, including old versions. Upgraders need nothing extra; fix those the registry rejects at startup. |
| 4 | Remove Progress overrides from commands; implement only ProgressAsync. |
| 5 | Change every ICommandHandler<TCommand, TState, TEvent> injection to ICommandHandler<TCommand>. Add CancellationToken to HandleAsync calls. |
| 6 | Remove AggregateCreationBehaviour and IInitialCommand marker-interface logic. |
| 7 | Convert saga classes from delegate-method to class : ISaga<TSagaState, TEvent> with ReactAsync, implemented once per class; several event types go through a marker interface. |
| 8 | Remove [Saga<TEvent, TIdProvider>] from event classes; implement Correlate on each saga instead, with its own prefix or metadata key. Remove AggregatesOptions.SagaKey. |
| 9 | Convert policy classes from delegate-method to class : IPolicy<TEvent> with ReactAsync, implemented once per class. Strip errorHandlingMode/maxErrors/maxErrorRate from [PolicyContract]; continueFrom stays. Error handling (retry + parked messages) is now built into the subscription infrastructure automatically. Read the event's metadata with MetadataScope.Current?.Snapshot() (see Reading the event's metadata). |
| 10 | Convert projection classes from delegate-method to class : IProjection<TEvent> with ProjectAsync(TEvent, EventMetadata, CancellationToken), implemented once per class. continueFrom stays. |
| 11 | Replace Aggregates.Sql with Aggregates.Projections.Sql, namespace included. Change IDbConnectionFactory.CreateConnection() into CreateAsync(cancellationToken), pass IsolationLevel.Unspecified where you relied on the provider's default, and copy ToTableValuedParameter if you use it. See SQL projections. |
| 12 | Replace MetadataAttribute<TContext> / IMetadataProvider<TContext> with a direct subclass of MetadataAttribute(key) overriding GetValueAsync. |
| 13 | Add null-checks on MetadataScope.Current (?.Add(...), ?.Snapshot()). Replace ToDictionary() with Snapshot(). MetadataScope is only IAsyncDisposable: open your own scopes with await using. |
| 14 | Import the positions of the 0.x persistent subscription groups with PersistentSubscriptionMigration (package Aggregates.KurrentDB.Migration) before the first 1.0 start, after stopping the writers and letting every group drain. Delete the groups only once 1.0 is accepted. Start the 1.0 hosts with RequireCheckpoint = true, listing the subscriptions that start fresh on purpose in AllowedWithoutCheckpoint. See Importing 0.x subscription positions. |
| 15 | Make Deserialize return null for unknown event types instead of throwing; a throwing Deserialize parks the event in every subscription that receives its type. |
| 16 | Check that every projection, policy and saga contract is unique across all three kinds: the contract is the subscription id. |
| 17 | Make the Correlate of every saga return exactly the 0.x saga id for in-flight 0.x sagas (read the Saga metadata key of events committed by 0.x); give new saga ids a prefix per saga. 0.x saga streams are read as they are. |
| 18 | Where a contract was bumped by two to replay history, set continueFrom: ContinueFrom.None instead: a bump of any size now continues from the nearest older version. See Contract versions. |
| 19 | Register the EventTypeRegistry in the container (services.AddSingleton(registry)) so subscriptions filter on event type in the store, as the 0.x groups did. See Event-type filter. |
| 20 | Replay or drop the parked messages of every 0.x group before the switch-over: 1.0 doesn't import them. Replay parked messages in 1.0 with IParkedMessages; set onError: SubscriptionErrorMode.Block on contracts that must keep the order. See Parked messages. |
| 21 | Resolve every difference in EventTypes in the dry-run: give a handler that relied on throwing to skip event types a marker interface on the types its 0.x group read. See Event-type filter. |
| 21 | Set SerializeMetadata and DeserializeMetadata, as a JSON object with the options 0.x used: without them, 1.0 stores no metadata and every handler sees EventMetadata.Empty. See Serialising metadata. |
| 22 | Use the JsonSerializerOptions of your 0.x UseJson(options) in Serialize and Deserialize. See Serialisation. |
| 23 | Add your own retry around HandleAsync where you relied on the 0.x retry of an append; 1.0 retries only a ConcurrencyException. See Retries. |
| 24 | Switch over all hosts of an environment at once. See All hosts at once. |
| 25 | Put [EventContract] on every event (Aggregates.Analyzers reports the missing ones), keep every stored event version in the registry, and give every contract a version of at least 1. Check that no aggregate or saga stream is truncated ($tb, $maxCount): 1.0 refuses to load it. See Serialisation. |
| 26 | Rename an EntityCommitDelegate you register yourself to CommitDelegate, and add the CancellationToken parameter to it and to SagaCommitDelegate. See Commit delegates. |