Aggregates.Projections.MSSP 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Aggregates.Projections.MSSP --version 1.0.0
                    
NuGet\Install-Package Aggregates.Projections.MSSP -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Aggregates.Projections.MSSP" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Aggregates.Projections.MSSP" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Aggregates.Projections.MSSP" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Aggregates.Projections.MSSP --version 1.0.0
                    
#r "nuget: Aggregates.Projections.MSSP, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Aggregates.Projections.MSSP@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Aggregates.Projections.MSSP&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Aggregates.Projections.MSSP&version=1.0.0
                    
Install as a Cake Tool

<img src="https://raw.githubusercontent.com/FleaFX/Aggregates/main/assets/logo.svg" alt="Aggregates" width="372">

Build & test

This library provides all the boilerplate code needed to do event sourcing, leaving you with just the core functionality of your domain to write.

Note: This is a ground-up rewrite of the existing Aggregates library (0.x), which stays on the legacy branch. To move from 0.x to 1.0, see Migrating from 0.x.

Packages

Package Description
Aggregates Core package: commands, aggregates, unit of work
Aggregates.Subscriptions Shared abstractions: ICheckpointStore, ISubscription, ISubscriptionFactory, IParkedMessageSink
Aggregates.Sagas Saga pattern: stateful event-driven process managers
Aggregates.Policies Policy pattern: stateless event-driven command dispatchers
Aggregates.Projections Projection pattern: event-driven read-model builders
Aggregates.Analyzers Opt-in analyser: reports event types without [EventContract] (AGG0001)

Storage integration packages are provided separately and are required to wire everything up:

Package Description
Aggregates.KurrentDB KurrentDB aggregate persistence
Aggregates.Sagas.KurrentDB KurrentDB saga storage + subscriptions
Aggregates.Policies.KurrentDB KurrentDB policy subscriptions
Aggregates.Projections.KurrentDB KurrentDB projection subscriptions
Aggregates.KurrentDB.Migration Imports 0.x persistent subscription positions as 1.0 checkpoints (switch-over only)
Aggregates.MSSP MSSP aggregate persistence
Aggregates.Sagas.MSSP MSSP saga storage + subscriptions
Aggregates.Policies.MSSP MSSP policy subscriptions
Aggregates.Projections.MSSP MSSP projection subscriptions
Aggregates.Projections.Sql SQL projection commits via ADO.NET

Getting started

Functional event sourcing

This library is based on two core functions from functional event sourcing.

The first takes a state and an event, and produces the next state:

state → event → state

Since an event is an irrejectable fact that has already happened, this function must always produce a new state — no exceptions allowed.

The second takes a state and a command, and produces a sequence of events:

state → command → events[]

A command is an intent, not a guarantee. This function is allowed to fail — this is where you validate input and enforce your domain rules. The produced sequence may contain one event, multiple events, or none at all.

IState

Implement IState<TState, TEvent> on your state object:

record ShoppingCartState(ImmutableDictionary<string, int> Items)
    : IState<ShoppingCartState, IShoppingCartEvent> {

    public static ShoppingCartState Initial => new(ImmutableDictionary<string, int>.Empty);

    public ShoppingCartState Apply(IShoppingCartEvent @event) => @event switch {
        ItemAdded e   => this with { Items = Items.SetItem(e.ItemId, Items.GetValueOrDefault(e.ItemId) + e.Quantity) },
        ItemRemoved e => this with { Items = Items.SetItem(e.ItemId, Items[e.ItemId] - e.Quantity) },
        _             => this
    };
}

ICommand

Implement ICommand<TState, TEvent> on your commands. The Id property identifies the target aggregate; ProgressAsync validates the current state and yields the resulting events:

record AddItem(AggregateIdentifier Id, string ItemId, int Quantity)
    : ICommand<ShoppingCartState, IShoppingCartEvent> {

    public async IAsyncEnumerable<IShoppingCartEvent> ProgressAsync(
        ShoppingCartState state,
        [EnumeratorCancellation] CancellationToken cancellationToken = default) {

        if (Quantity <= 0) throw new ArgumentOutOfRangeException(nameof(Quantity));
        yield return new ItemAdded(ItemId, Quantity);
    }
}

Handling commands

Inject ICommandHandler<TCommand> wherever you need it:

class ShoppingCartController(ICommandHandler<AddItem> handler) : ControllerBase {
    [HttpPost("{id:guid}")]
    public async Task<IActionResult> Post(Guid id, [FromBody] AddItemRequest request, CancellationToken ct) {
        await handler.HandleAsync(new AddItem(id.ToString(), request.ItemId, request.Quantity), ct);
        return Ok();
    }
}

Wiring up

KurrentDB:

services
    .AddAggregates(o => o.ScanAssemblies(typeof(AddItem).Assembly))
    .AddKurrentDb(o => {
        o.Serialize   = e => new SerializedEvent(e.GetType().Name, JsonSerializer.SerializeToUtf8Bytes(e));
        o.Deserialize = (type, data) => /* your deserializer */;
    });

MSSP:

services
    .AddAggregates(o => o.ScanAssemblies(typeof(AddItem).Assembly))
    .AddMssp(o => {
        o.Serialize   = e => new EventData(e.GetType().Name, JsonSerializer.SerializeToUtf8Bytes(e));
        o.Deserialize = (type, data) => /* your deserializer */;
    });

ScanAssemblies discovers all ICommand<TState, TEvent> implementations in the given assemblies and registers a handler for each. To register an explicit set of commands instead, use ScanTypes(typeof(AddItem), ...); AddSagas, AddPolicies and AddProjections offer the same choice.


Sagas

A saga is a stateful process manager that reacts to a stream of domain events by dispatching commands. Unlike a policy, a saga maintains its own state across multiple events.

ISaga

Implement ISaga<TSagaState, TEvent> to define the routing and the reaction logic. Correlate returns the saga instance(s) an event belongs to (their ids are the names of their saga streams); ReactAsync receives the state of such an instance before the triggering event, and the event, and yields zero or more commands:

[SagaContract("OrderFulfillment")]
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, IOrderEvent> {

    public IEnumerable<AggregateIdentifier> Correlate(IOrderEvent @event, EventMetadata metadata) =>
        [new AggregateIdentifier($"order-fulfillment-{@event.OrderId}")];

    public async IAsyncEnumerable<ICommand> ReactAsync(
        OrderFulfillmentState state,
        IOrderEvent @event,
        [EnumeratorCancellation] CancellationToken cancellationToken = default) {

        if (@event is OrderPlaced placed && !state.IsShipped)
            yield return new ShipOrder(placed.OrderId);
    }
}

The saga state uses the same IState<TState, TEvent> pattern as aggregates:

record OrderFulfillmentState(bool IsShipped) : IState<OrderFulfillmentState, IOrderEvent> {
    public static OrderFulfillmentState Initial => new(false);

    public OrderFulfillmentState Apply(IOrderEvent @event) => @event switch {
        OrderShipped => this with { IsShipped = true },
        _            => this
    };
}

SagaContractAttribute

Decorate your saga class with [SagaContract] to assign it a stable identity for checkpointing and versioning:

[SagaContract("OrderFulfillment", version: 1, @namespace: "Orders", startFromEnd: false)]
class OrderFulfillmentSaga : ISaga<OrderFulfillmentState, IOrderEvent> { ... }

startFromEnd: true causes the saga to start consuming only new events on its first run, skipping the existing history.

Wiring up sagas

KurrentDB:

services
    .AddAggregates(o => o.ScanAssemblies(typeof(ShipOrder).Assembly))
    .AddKurrentDb(o => { /* serialization */ });

services
    .AddAggregates()
    .AddSagas(o => o.ScanAssemblies(typeof(OrderFulfillmentSaga).Assembly))
    .AddKurrentDb();

MSSP:

services
    .AddAggregates(o => o.ScanAssemblies(typeof(ShipOrder).Assembly))
    .AddMssp(o => { /* serialization */ });

services
    .AddAggregates()
    .AddSagas(o => o.ScanAssemblies(typeof(OrderFulfillmentSaga).Assembly))
    .AddMssp();

Every saga in the scanned assemblies gets a subscription hosted service, which routes each event with the saga's Correlate. Give each saga its own id prefix: two sagas that return the same id share a saga stream.


Policies

A policy is a stateless event-driven reaction: it receives an event and dispatches zero or more commands, with no state of its own.

IPolicy

Implement IPolicy<TEvent> to define the reaction logic:

[PolicyContract("SendWelcomeEmail")]
class SendWelcomeEmailPolicy : IPolicy<UserRegistered> {

    public async IAsyncEnumerable<ICommand> ReactAsync(
        UserRegistered @event,
        [EnumeratorCancellation] CancellationToken cancellationToken = default) {

        yield return new SendEmail(@event.UserId, "Welcome!");
    }
}

Wiring up policies

KurrentDB:

services
    .AddAggregates(o => o.ScanAssemblies(typeof(SendEmail).Assembly))
    .AddKurrentDb(o => { /* serialization */ });

services
    .AddAggregates()
    .AddPolicies(o => o.ScanAssemblies(typeof(SendWelcomeEmailPolicy).Assembly))
    .AddKurrentDb();

MSSP:

services
    .AddAggregates(o => o.ScanAssemblies(typeof(SendEmail).Assembly))
    .AddMssp(o => { /* serialization */ });

services
    .AddAggregates()
    .AddPolicies(o => o.ScanAssemblies(typeof(SendWelcomeEmailPolicy).Assembly))
    .AddMssp();

The subscription hosted service is registered automatically for every scanned policy.


Projections

A projection listens to a stream of domain events and builds a read model by writing to an external store (e.g. a SQL database). Unlike sagas and policies, projections do not dispatch commands — they produce writes.

IProjection

Implement IProjection<TEvent> to define the projection logic. The method returns an ICommit that describes the pending writes; the infrastructure executes it after the method returns:

[ProjectionContract("Orders")]
class OrdersProjection(IDbConnectionFactory db) : IProjection<IOrdersProjectionEvent> {

    public ValueTask<ICommit> ProjectAsync(
        IOrdersProjectionEvent @event,
        CancellationToken cancellationToken = default) =>

        ValueTask.FromResult<ICommit>(@event switch {
            OrderPlaced e  => Commit.Create().UseSql(db)
                                .Query("INSERT INTO orders (id, date) VALUES (@Id, @Date)",
                                       new { e.Id, e.Date }),
            OrderShipped e => Commit.Create().UseSql(db)
                                .Query("UPDATE orders SET shipped = 1 WHERE id = @Id",
                                       new { e.Id }),
            _              => Commit.Create()
        });
}

Wiring up projections

KurrentDB:

services
    .AddProjections(o => o.ScanAssemblies(typeof(OrdersProjection).Assembly))
    .AddKurrentDb();

MSSP:

services
    .AddProjections(o => o.ScanAssemblies(typeof(OrdersProjection).Assembly))
    .AddMssp();

ScanAssemblies discovers all IProjection<TEvent> implementations and registers a subscription hosted service for each. AddKurrentDb/AddMssp supplies the ISubscriptionFactory and ICheckpointStore.


Running the tests

dotnet test --solution src/Aggregates.slnx

The integration tests run against real stores and need Docker: KurrentDB and SQL Server are started in containers through Testcontainers, and MSSP runs embedded. Without Docker, they fail rather than being skipped. To run only the unit tests:

dotnet test --solution src/Aggregates.slnx --filter "Category!=Integration"

Integration tests are marked with [Trait("Category", "Integration")]. Tests for known bugs are skipped; the reasons are listed in src/Aggregates.Tests/Testing/KnownIssues.cs.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 91 11/17/2026
1.0.1 95 11/16/2026
1.0.0 128 10/24/2026
1.0.0-preview.23 66 10/23/2026
1.0.0-preview.22 63 10/23/2026
1.0.0-preview.21 68 10/23/2026
1.0.0-preview.19 77 10/20/2026
1.0.0-preview.18 73 10/20/2026
1.0.0-preview.17 71 10/20/2026
1.0.0-preview.16 62 10/19/2026
1.0.0-preview.15 69 10/16/2026
1.0.0-preview.14 70 10/16/2026
1.0.0-preview.13 67 10/16/2026
1.0.0-preview.12 72 10/15/2026
1.0.0-preview.11 74 10/15/2026
1.0.0-preview.9 66 10/15/2026
1.0.0-preview.8 73 10/14/2026
1.0.0-preview.7 71 10/14/2026
1.0.0-preview.6 103 6/12/2026
1.0.0-preview.5 89 5/25/2026
Loading failed