Lesson 35 of 40
Architecture
Expert
60 min
Event Sourcing & CQRS
Implement Event Sourcing with Marten, the Aggregate pattern, projections, and combine it with CQRS for a complete event-driven architecture.
Part 1: Event Store with Marten
builder.Services.AddMarten(opts =>
{
opts.Connection(connectionString);
opts.Projections.Add<OrderProjection>(ProjectionLifecycle.Inline);
}).UseLightweightSessions();
// Append events to stream
session.Events.Append(orderId, new OrderPlaced(orderId, items));
await session.SaveChangesAsync();
{
opts.Connection(connectionString);
opts.Projections.Add<OrderProjection>(ProjectionLifecycle.Inline);
}).UseLightweightSessions();
// Append events to stream
session.Events.Append(orderId, new OrderPlaced(orderId, items));
await session.SaveChangesAsync();
Part 2: Aggregate Pattern
public class Order
{
public Guid Id { get; private set; }
public OrderStatus Status { get; private set; }
public void Apply(OrderPlaced e) => Status = OrderStatus.Placed;
public void Apply(OrderShipped e) => Status = OrderStatus.Shipped;
}
{
public Guid Id { get; private set; }
public OrderStatus Status { get; private set; }
public void Apply(OrderPlaced e) => Status = OrderStatus.Placed;
public void Apply(OrderShipped e) => Status = OrderStatus.Shipped;
}
Part 3: Projections for Read Models
public class OrderSummaryProjection : SingleStreamProjection<OrderSummary>
{
public OrderSummary Create(OrderPlaced e) =>
new() { Id = e.OrderId, Status = "Placed" };
public void Apply(OrderShipped e, OrderSummary view)
=> view.Status = "Shipped";
}
{
public OrderSummary Create(OrderPlaced e) =>
new() { Id = e.OrderId, Status = "Placed" };
public void Apply(OrderShipped e, OrderSummary view)
=> view.Status = "Shipped";
}
Part 4: Event Replay & Debugging
One of Event Sourcing's biggest advantages is full auditability. In VS 2026's Marten integration:
- View event stream history in the Diagnostics panel
- Replay events to rebuild projections
- Time-travel queries: rebuild state at any point in time
- Debugging: see exact sequence of events that led to current state