Skip to content

Getting Started

Kieron Lanning edited this page Apr 16, 2026 · 1 revision

Getting Started

1. Install packages

<ItemGroup>
  <PackageReference Include="EventSourcing" />
  <PackageReference Include="Purview.EventSourcing.SourceGenerator" PrivateAssets="all" />
</ItemGroup>

Add a provider package based on your persistence choice, for example:

<PackageReference Include="EventSourcing.SqlServer.Events" />
<PackageReference Include="EventSourcing.SqlServer.Snapshot" />

2. Define an aggregate

using Purview.EventSourcing.Aggregates;

[GenerateAggregate]
public partial class OrderAggregate : AggregateBase
{
    public string CustomerId { get; private set; } = default!;
    public decimal Total { get; private set; }

    [GenerateAggregateEvent]
    public partial void CreateOrder(string customerId);

    [GenerateAggregateEvent]
    public partial void AddLineItem(string productId, string productName, int quantity, decimal unitPrice);
}

The source generator creates:

  • event classes
  • partial method bodies
  • event registration
  • apply methods

3. Register stores

builder.Services.AddSqlServerEventStore();
builder.Services.AddSqlServerSnapshotQueryableEventStore();
{
  "ConnectionStrings": {
    "eventstore-sqlserver": "Server=.;Database=MyApp;Trusted_Connection=True;"
  }
}

4. Use the facades

Command-side usage

public sealed class OrderService(IEventStore store)
{
    public async Task CreateAsync(string id, string customerId, CancellationToken cancellationToken)
    {
        var order = await store.CreateAsync<OrderAggregate>(id, cancellationToken: cancellationToken);
        order.CreateOrder(customerId);
        await store.SaveAsync(order, cancellationToken);
    }
}

Query-side usage

public sealed class OrderQueries(IQueryableEventStore store)
{
    public Task<long> CountAsync(CancellationToken cancellationToken) =>
        store.CountAsync<OrderAggregate>(null, cancellationToken);
}

5. Add transactions when a workflow touches multiple aggregates

await using var transaction = transactionFactory.Create();
transaction.Enlist(order, store);
transaction.Enlist(inventory, store);

var result = await transaction.CommitAsync(cancellationToken);

See Transactions for the detailed behavior model.

Clone this wiki locally