Recipes
Add a command handler
- Define the command in the contracts assembly:
public record ProcessPayment(Guid OrderId, decimal Amount) : ICommand; - Implement exactly one
ICommandHandler<ProcessPayment>. - Make sure its assembly is passed to
AddHandlersFromAssemblies(...).
public class PaymentCommandHandler : ICommandHandler<ProcessPayment>
{
public Task HandleAsync(ProcessPayment command, CancellationToken cancellationToken) { /* ... */ return Task.CompletedTask; }
}
A second handler for the same command fails at startup. If several parties must react, model it as an event.
Publish an event from an aggregate
public class Order : AggregateRoot
{
public static Order Create(decimal total)
{
var order = new Order { Id = Guid.NewGuid(), Total = total };
order.RaiseDomainEvent(new OrderPlaced(order.Id, total));
return order;
}
}
db.Orders.Add(Order.Create(total));
await db.SaveChangesAsync(ct); // DomainEventInterceptor writes the outbox row in the same transaction
Requires DomainEventInterceptor on the DbContext and AddOpinionatedEventingEntityFramework<TDbContext>().
Publish from application code
await publisher.PublishEventAsync(new OrderPlaced(order.Id, total), ct);
await db.SaveChangesAsync(ct);
Write an orchestrated saga
- State class (POCO, serialised to JSON).
- Class deriving
SagaOrchestrator<TState>withStartWith,Then, optionalCompensateWith,ExpireAfter,OnTimeout. ctx.Complete()in the final step.services.AddOpinionatedEventingSagas(); services.AddSaga<MySaga>();modelBuilder.ApplySagaStateConfiguration(Database.ProviderName)and a migration.
Full example: Saga Orchestration. For stateless flows use choreography.
Make a handler idempotent
Pick the cheapest that fits: natural idempotency, unique constraint on IMessagingContext.MessageId, or pass the message ID as an idempotency key to an external API. See Idempotency.
Test a handler
Handlers are plain classes. Construct them and call HandleAsync.
var handler = new PaymentCommandHandler();
await handler.HandleAsync(new ProcessPayment(orderId, 10m), CancellationToken.None);
Test a saga participant
var ctx = new FakeSagaContext { CorrelationId = Guid.NewGuid() };
await new FulfillmentParticipant(fakeInventory).HandleAsync(evt, ctx, CancellationToken.None);
Assert.Single(ctx.PublishedEvents.OfType<StockReserved>());
Test aggregates and the outbox
var order = Order.Create(100m);
Assert.Single(order.DomainEvents); // no database needed
services.AddSingleton<IOutboxStore, InMemoryOutboxStore>(); // store.PendingMessages after SaveChanges
Test saga timeouts
Register FakeTimeProvider as TimeProvider and call clock.Advance(TimeSpan.FromMinutes(31)).
Run locally
Use the Aspire AppHost extensions (AddRabbitMqMessaging / AddAzureServiceBusEmulator). See Local Development.
Enable CloudEvents
Not documented yet. Do not invent configuration; tell the user it is not covered.