# OpinionatedEventing > OpinionatedEventing is an opinionated event-driven messaging library for .NET (outbox-first, commands vs events, sagas, DDD aggregates; Azure Service Bus and RabbitMQ transports). There is no direct-to-broker publish API: IPublisher always writes to the transactional outbox. --- Source: https://opinionated-eventing.com/docs/ai/agent-guide # Agent Guide OpinionatedEventing is new and opinionated. AI assistants often guess its API from MassTransit, NServiceBus or MediatR. Those guesses are usually wrong. Read this page before writing code that uses the library. Other pages for agents: [API cheat sheet](https://opinionated-eventing.com/docs/ai/api-cheat-sheet.md), [Which package do I need?](https://opinionated-eventing.com/docs/ai/packages.md), [Recipes](https://opinionated-eventing.com/docs/ai/recipes.md), [Coming from MassTransit / NServiceBus / MediatR](https://opinionated-eventing.com/docs/ai/migration-mapping.md), [Instruction templates](https://opinionated-eventing.com/docs/ai/templates.md). Machine-readable indexes: [`/llms.txt`](https://opinionated-eventing.com/llms.txt) and [`/llms-full.txt`](https://opinionated-eventing.com/llms-full.txt). ## Design rules 1. **There is no direct publish path.** `IPublisher` writes to the outbox table in the caller's transaction. A background worker forwards it to the broker. Never inject a broker client (`ServiceBusClient`, `IConnection`, ...) to publish. 2. **Commands and events are different things.** - `ICommand`: "please do X". Exactly **one** `ICommandHandler` per command type. A second registration throws `InvalidOperationException` at startup. - `IEvent`: "X happened". **Zero or more** `IEventHandler`. 3. **Send commands with `SendCommandAsync`, publish events with `PublishEventAsync`.** Both live on `IPublisher`. 4. **Delivery is at-least-once.** Handlers must tolerate duplicates. See [Idempotency](https://opinionated-eventing.com/docs/idempotency.md). 5. **Aggregates raise events, they do not publish.** Extend `AggregateRoot` and call `RaiseDomainEvent(...)`. The `DomainEventInterceptor` writes the outbox rows during `SaveChangesAsync`. Never inject `IPublisher` into an aggregate. 6. **One `SaveChangesAsync` commits business data and outbox rows together.** Do not call it inside aggregate methods. 7. **Handler classes are registered by scanning.** Use `AddHandlersFromAssemblies`. Do not register `ICommandHandler` / `IEventHandler` by hand. 8. **Sagas are registered explicitly.** `AddSaga()` for orchestrators, `AddSagaParticipant()` for choreography participants. Both register the underlying event subscriptions for you. 9. **Transport is a DI choice.** Handler, aggregate and saga code never changes between Azure Service Bus and RabbitMQ. 10. **Name messages by intent.** Events in past tense (`OrderPlaced`), commands imperative (`ProcessPayment`). Avoid `OrderUpdated`, `DoSomething`. ## Wiring order in `Program.cs` ```csharp // 1. Core + handlers + outbox services .AddOpinionatedEventing() .AddHandlersFromAssemblies(Assembly.GetExecutingAssembly()) .AddOutbox(); // 2. EF Core: interceptor on the DbContext, then the store services.AddDbContext((sp, options) => { options.UseSqlServer(connectionString); options.AddInterceptors(sp.GetRequiredService()); }); services.AddOpinionatedEventingEntityFramework(); // 3. Sagas (only if used) services.AddOpinionatedEventingSagas(); services.AddSaga(); // 4. Exactly one transport services.AddRabbitMQTransport(o => { o.ConnectionString = "..."; o.ServiceName = "order-service"; }); // or: services.AddAzureServiceBusTransport(o => { ... }); ``` In `OnModelCreating` call `modelBuilder.ApplyOutboxConfiguration(Database.ProviderName)` (and `ApplySagaStateConfiguration(...)` when using sagas), then add an EF migration. ## Do / Don't | Don't | Do | |---|---| | Publish to the broker directly | `await publisher.PublishEventAsync(evt, ct)` then `SaveChangesAsync` | | Write two handlers for one command | One `ICommandHandler`; use an event if several parties must react | | Send a "command" with `PublishEventAsync` | `SendCommandAsync` for commands | | Assume exactly-once delivery | Make handlers idempotent (natural, unique constraint, or message ID key) | | Inject `IPublisher` into an aggregate | `RaiseDomainEvent(...)` | | Call `SaveChanges` in a domain method | Let the application layer save once | | Mix `ApplyOutboxConfiguration()` with `CreateOutboxTable()` | Pick one migration approach per project | | Use `DateTime.UtcNow` in saga timeouts | Inject `TimeProvider`; use `FakeTimeProvider` in tests | | Register a saga handler by hand | `AddSaga()` / `AddSagaParticipant()` | | Stand up real brokers in unit tests | Use `OpinionatedEventing.Testing` fakes | ## When unsure Check the [API cheat sheet](https://opinionated-eventing.com/docs/ai/api-cheat-sheet.md) first. If an API you want is not on it, do not invent one. Look in the matching docs page, or tell the user the API is not documented. --- Source: https://opinionated-eventing.com/docs/ai/api-cheat-sheet # API Cheat Sheet Targets .NET 10 and 11. Only APIs that appear in the documentation are listed. If something is not here, do not guess; see the [Agent guide](https://opinionated-eventing.com/docs/ai/agent-guide.md). ## Messages ```csharp using OpinionatedEventing; public record OrderPlaced(Guid OrderId, decimal Total) : IEvent; // past tense public record ProcessPayment(Guid OrderId, decimal Amount) : ICommand; // imperative [MessageTopic("payments.events.order-placed")] // optional override, events public record PaymentReceived(Guid OrderId, Guid PaymentId) : IEvent; [MessageQueue("payments.commands.cancel-payment")] // optional override, commands public record CancelPayment(Guid OrderId, string Reason) : ICommand; ``` Default broker names are derived from the type name: `OrderPlaced` becomes topic/exchange `order-placed`, `ProcessPayment` becomes queue `process-payment`. *Package: `OpinionatedEventing.Abstractions`.* ## Handlers ```csharp public class NotifyHandler : IEventHandler // 0..n per event { public Task HandleAsync(OrderPlaced @event, CancellationToken cancellationToken) => Task.CompletedTask; } public class PaymentHandler : ICommandHandler // exactly 1 per command { public Task HandleAsync(ProcessPayment command, CancellationToken cancellationToken) => Task.CompletedTask; } ``` ## Publishing (always via the outbox) ```csharp public class OrderService(IPublisher publisher, AppDbContext db) { public async Task PlaceAsync(CancellationToken ct) { await publisher.PublishEventAsync(new OrderPlaced(id, total), ct); // fan-out await publisher.SendCommandAsync(new ProcessPayment(id, total), ct); // point-to-point await db.SaveChangesAsync(ct); // commits business rows + outbox rows atomically } } ``` ## Aggregates ```csharp public class Order : AggregateRoot { public void Cancel(string reason) => RaiseDomainEvent(new OrderCancelled(Id, reason)); } // aggregate.DomainEvents: IReadOnlyList, inspect in tests. // ClearDomainEvents() is internal: only the framework calls it, never application code. ``` ## Registration ```csharp services.AddOpinionatedEventing(options => // options are optional { options.Outbox.PollInterval = TimeSpan.FromSeconds(1); options.Outbox.BatchSize = 50; options.Outbox.MaxAttempts = 5; options.Outbox.ConcurrentWorkers = 1; options.Outbox.MaxRetryDelay = TimeSpan.FromMinutes(5); options.Outbox.ProcessedRetention = TimeSpan.FromDays(7); // null = keep forever options.Outbox.FailedRetention = null; options.Outbox.CleanupInterval = TimeSpan.FromHours(1); }) .AddHandlersFromAssemblies(Assembly.GetExecutingAssembly()) .AddOutbox(); services.AddOpinionatedEventingEntityFramework(); services.AddOpinionatedEventingSagas(o => o.TimeoutCheckInterval = TimeSpan.FromSeconds(30)); // options optional services.AddSaga(); services.AddSagaParticipant(); services.AddRabbitMQTransport(o => { o.ConnectionString = "..."; o.ServiceName = "order-service"; o.AutoDeclareTopology = true; }); services.AddAzureServiceBusTransport(o => { o.ConnectionString = "..."; o.ServiceName = "order-service"; o.AutoCreateResources = true; }); ``` ## EF Core ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyOutboxConfiguration(Database.ProviderName); modelBuilder.ApplySagaStateConfiguration(Database.ProviderName); // only with sagas } options.AddInterceptors(sp.GetRequiredService()); // Alternative to model-based migrations (do not mix): migrationBuilder.CreateOutboxTable(); migrationBuilder.CreateSagaStateTable(); migrationBuilder.DropOutboxTable(); migrationBuilder.DropSagaStateTable(); migrationBuilder.AddOutboxRetentionColumns(); // incremental upgrade ``` ## Sagas ```csharp public class OrderSaga : SagaOrchestrator { protected override void Configure(ISagaBuilder builder) => builder .StartWith(async (evt, state, ctx) => await ctx.SendCommandAsync(new ProcessPayment(evt.OrderId, evt.Total))) .Then((evt, state, ctx) => { ctx.Complete(); return Task.CompletedTask; }) .CompensateWith(async (evt, state, ctx) => await ctx.SendCommandAsync(new CancelPayment(state.OrderId, evt.Reason))) .ExpireAfter(TimeSpan.FromMinutes(30)) // or ExpireAt(DateTimeOffset) .OnTimeout(async (state, ctx) => await ctx.SendCommandAsync(new CancelPayment(state.OrderId, "Timed out"))); // builder.CorrelateBy(evt => evt.OrderId.ToString()) to correlate by payload } public class FulfillmentParticipant : ISagaParticipant // choreography { public Task HandleAsync(PaymentReceived @event, ISagaContext ctx, CancellationToken ct) => ctx.PublishEventAsync(new StockReserved(ctx.CorrelationId, "SKU", 1), ct); } ``` `ISagaContext`: `CorrelationId`, `SendCommandAsync`, `PublishEventAsync`, `Complete()`. Saga statuses: `Active`, `Completed`, `Compensating`, `Failed`, `TimedOut`. ## Context, monitoring, health ```csharp IMessagingContext // CorrelationId, CausationId, MessageId of the message being handled IOutboxMonitor // GetPendingCountAsync(ct), GetDeadLetterCountAsync(ct) services.AddHealthChecks().AddOpinionatedEventingHealthChecks(o => { o.OutboxBacklogThreshold = 100; o.SagaTimeoutBacklogThreshold = 10; }); services.AddOpenTelemetry() .WithTracing(t => t.AddOpinionatedEventingInstrumentation()) .WithMetrics(m => m.AddOpinionatedEventingMetrics()); ``` ## Aspire AppHost ```csharp var rabbit = builder.AddRabbitMqMessaging("rabbitmq"); var asb = builder.AddAzureServiceBusEmulator("servicebus"); builder.AddProject("api").WithReference(rabbit); ``` ## Testing (`OpinionatedEventing.Testing`) ```csharp services.AddSingleton(); // store.PendingMessages services.AddSingleton(new InMemorySagaStateStore()); services.AddSingleton(new FakeTimeProvider()); // clock.Advance(...) var ctx = new FakeSagaContext { CorrelationId = Guid.NewGuid() }; // ctx.SentCommands, ctx.PublishedEvents, ctx.IsCompleted, ctx.SentCommands, ctx.PublishedEvents (IReadOnlyList; use .OfType()) ``` --- Source: https://opinionated-eventing.com/docs/ai/packages # Which package do I need? ## By project role | Project does... | Install | |---|---| | Defines messages only (contracts / domain assembly) | `OpinionatedEventing.Abstractions` | | Handles messages in a service host | `OpinionatedEventing` + one transport | | Publishes events or sends commands | `OpinionatedEventing` + `OpinionatedEventing.Outbox` + `OpinionatedEventing.EntityFramework` + one transport | | Uses sagas (orchestration or choreography) | Add `OpinionatedEventing.Sagas` | | Tests handlers, sagas, aggregates | `OpinionatedEventing.Testing` (test projects only) | | Local dev with Aspire | Aspire AppHost package(s), see below | | Tracing and metrics | `OpinionatedEventing.OpenTelemetry` | Receive-only services do not need EF Core. ## Package map | Package | Contains | |---|---| | `OpinionatedEventing.Abstractions` | `IEvent`, `ICommand`, `IEventHandler`, `ICommandHandler`, `IPublisher`, `AggregateRoot`, `[MessageTopic]`, `[MessageQueue]` | | `OpinionatedEventing` | `AddOpinionatedEventing`, `AddHandlersFromAssemblies`, `OpinionatedEventingOptions`, `IMessagingContext` | | `OpinionatedEventing.Outbox` | `AddOutbox`, `OutboxDispatcherWorker`, `OutboxCleanupWorker`, `IOutboxStore`, `IOutboxMonitor` | | `OpinionatedEventing.EntityFramework` | `AddOpinionatedEventingEntityFramework`, `DomainEventInterceptor`, `ApplyOutboxConfiguration`, `ApplySagaStateConfiguration`, migration helpers | | `OpinionatedEventing.Sagas` | `AddOpinionatedEventingSagas`, `AddSaga`, `AddSagaParticipant`, `SagaOrchestrator`, `ISagaParticipant`, `ISagaContext` | | `OpinionatedEventing.AzureServiceBus` | `AddAzureServiceBusTransport` | | `OpinionatedEventing.RabbitMQ` | `AddRabbitMQTransport` | | `OpinionatedEventing.OpenTelemetry` | `AddOpinionatedEventingInstrumentation`, `AddOpinionatedEventingMetrics` | | `OpinionatedEventing.Aspire` | `AddOpinionatedEventingHealthChecks` | | `OpinionatedEventing.Aspire.AzureServiceBus` | AppHost `AddAzureServiceBusEmulator` | | `OpinionatedEventing.Aspire.RabbitMQ` | AppHost `AddRabbitMqMessaging` | | `OpinionatedEventing.Testing` | `InMemoryOutboxStore`, `InMemorySagaStateStore`, `FakeSagaContext`, `FakePublisher` | Pick **one** transport per service. :::note Targets .NET 10 and 11. `AddOpinionatedEventingHealthChecks` comes from `OpinionatedEventing.Aspire`; the AppHost extensions (`AddRabbitMqMessaging`, `AddAzureServiceBusEmulator`) are documented under the same Aspire package in [Local Development](https://opinionated-eventing.com/docs/local-development.md), while the homepage lists transport-specific `OpinionatedEventing.Aspire.*` packages. Check NuGet for the exact package IDs before adding references. ::: --- Source: https://opinionated-eventing.com/docs/ai/recipes # Recipes ## Add a command handler 1. Define the command in the contracts assembly: `public record ProcessPayment(Guid OrderId, decimal Amount) : ICommand;` 2. Implement exactly one `ICommandHandler`. 3. Make sure its assembly is passed to `AddHandlersFromAssemblies(...)`. ```csharp public class PaymentCommandHandler : ICommandHandler { 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 ```csharp 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()`. ## Publish from application code ```csharp await publisher.PublishEventAsync(new OrderPlaced(order.Id, total), ct); await db.SaveChangesAsync(ct); ``` ## Write an orchestrated saga 1. State class (POCO, serialised to JSON). 2. Class deriving `SagaOrchestrator` with `StartWith`, `Then`, optional `CompensateWith`, `ExpireAfter`, `OnTimeout`. 3. `ctx.Complete()` in the final step. 4. `services.AddOpinionatedEventingSagas(); services.AddSaga();` 5. `modelBuilder.ApplySagaStateConfiguration(Database.ProviderName)` and a migration. Full example: [Saga Orchestration](https://opinionated-eventing.com/docs/sagas-orchestration.md). For stateless flows use [choreography](https://opinionated-eventing.com/docs/sagas-choreography.md). ## 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](https://opinionated-eventing.com/docs/idempotency.md). ## Test a handler Handlers are plain classes. Construct them and call `HandleAsync`. ```csharp var handler = new PaymentCommandHandler(); await handler.HandleAsync(new ProcessPayment(orderId, 10m), CancellationToken.None); ``` ## Test a saga participant ```csharp var ctx = new FakeSagaContext { CorrelationId = Guid.NewGuid() }; await new FulfillmentParticipant(fakeInventory).HandleAsync(evt, ctx, CancellationToken.None); Assert.Single(ctx.PublishedEvents.OfType()); ``` ## Test aggregates and the outbox ```csharp var order = Order.Create(100m); Assert.Single(order.DomainEvents); // no database needed services.AddSingleton(); // 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](https://opinionated-eventing.com/docs/local-development.md). ## Enable CloudEvents Not documented yet. Do not invent configuration; tell the user it is not covered. --- Source: https://opinionated-eventing.com/docs/ai/migration-mapping # Coming from MassTransit / NServiceBus / MediatR | Other library | OpinionatedEventing | |---|---| | MassTransit `IConsumer` | `IEventHandler` (events) or `ICommandHandler` (commands) | | NServiceBus `IHandleMessages` | same as above | | MediatR `IRequestHandler` | `ICommandHandler` (but asynchronous via a broker, no return value) | | MediatR `INotificationHandler` | `IEventHandler` | | MassTransit `IPublishEndpoint.Publish` | `IPublisher.PublishEventAsync` (outbox) | | MassTransit `ISendEndpoint.Send` / NServiceBus `Send` | `IPublisher.SendCommandAsync` (outbox) | | MassTransit / NServiceBus transactional outbox | Built in and **the only publish path** | | MassTransit `MassTransitStateMachine` / NServiceBus `Saga` | `SagaOrchestrator` with `StartWith` / `Then` / `CompensateWith` | | Process-manager-less choreography | `ISagaParticipant` | | `AddMassTransit(x => x.UsingRabbitMq(...))` | `AddOpinionatedEventing().AddHandlersFromAssemblies(...).AddOutbox()` + `AddRabbitMQTransport(...)` | | Correlation / conversation IDs | `CorrelationId` / `CausationId` via `IMessagingContext` | ## Things that do not exist here - Publishing directly to the broker, or skipping the outbox. - Request/response (`IRequestClient`, `Send` returning a reply). - Mediator-style in-process dispatch of commands with return values. - Multiple handlers for one command. - Configuring endpoints, consumers or retry middleware per consumer in code. Topology is derived from message types (override with `[MessageTopic]` / `[MessageQueue]`). When a library feature from this list is requested, explain that it is a deliberate omission and propose the event/command equivalent. --- Source: https://opinionated-eventing.com/docs/ai/templates # Agent Instruction Templates Copy one of these into your own repository so your coding agent follows the library's rules. They are deliberately short and point at the website for details. ## Base rules (any agent) Use for `AGENTS.md`, Cursor rules, or any agent that reads plain Markdown. ````markdown ## OpinionatedEventing This project uses OpinionatedEventing (https://opinionated-eventing.com). It is newer than most model training data. Do not guess the API. Read https://opinionated-eventing.com/llms.txt and https://opinionated-eventing.com/docs/ai/agent-guide first. Rules: - Publish only through `IPublisher` (`PublishEventAsync` for events, `SendCommandAsync` for commands). It writes to the outbox. Never publish to the broker directly. There is no such API. - `ICommand`: exactly one `ICommandHandler`. `IEvent`: zero or more `IEventHandler`. - Delivery is at-least-once: handlers must be idempotent. - Aggregates extend `AggregateRoot` and call `RaiseDomainEvent`. Never inject `IPublisher` into them. - Register handlers with `AddHandlersFromAssemblies`; sagas with `AddSaga` / `AddSagaParticipant`. - Call `SaveChangesAsync` once in the application layer; it commits business data and outbox rows together. - Test with `OpinionatedEventing.Testing` (`InMemoryOutboxStore`, `InMemorySagaStateStore`, `FakeSagaContext`). - If an API is not in https://opinionated-eventing.com/docs/ai/api-cheat-sheet, do not invent it. ```` ## GitHub Copilot Save as `.github/copilot-instructions.md` (or append to it). Use the base rules above verbatim. ## Claude Code Save the base rules in `CLAUDE.md` at your repository root (or `AGENTS.md` and import it with `@AGENTS.md`). For a reusable Claude skill, create `.claude/skills/opinionated-eventing/SKILL.md`: ````markdown --- name: opinionated-eventing description: Use when adding or changing messaging code (commands, events, handlers, outbox, sagas, aggregates) in a project that references OpinionatedEventing packages. --- Before writing code, fetch https://opinionated-eventing.com/llms-full.txt (or read https://opinionated-eventing.com/docs/ai/agent-guide and /docs/ai/api-cheat-sheet) and follow it. Never publish directly to a broker. Do not invent APIs that are not in the cheat sheet. ```` ## Other agents Cursor, Windsurf, Gemini CLI, Aider and others: paste the base rules into the agent's rules or context file. --- Source: https://opinionated-eventing.com/docs/getting-started # Getting Started This guide walks you through installing OpinionatedEventing, picking a transport, registering handlers, and publishing your first event end-to-end. ## Prerequisites - .NET 10 or 11 - An Azure Service Bus namespace **or** a RabbitMQ broker (or run either locally via [Aspire](https://opinionated-eventing.com/docs/local-development.md)) - Entity Framework Core (only required if the service **publishes** messages or uses sagas — receive-only services do not need it) ## 1. Install packages The packages you need depend on what the service does. **Domain / contracts assembly** (only needs marker interfaces and base types): ``` dotnet add package OpinionatedEventing.Abstractions ``` **Service host** (handles or publishes messages — needs DI registration and runtime): ``` dotnet add package OpinionatedEventing # Pick one transport: dotnet add package OpinionatedEventing.AzureServiceBus dotnet add package OpinionatedEventing.RabbitMQ ``` **Service that publishes** (also sends events or commands): ``` dotnet add package OpinionatedEventing dotnet add package OpinionatedEventing.Outbox dotnet add package OpinionatedEventing.EntityFramework # Pick one transport: dotnet add package OpinionatedEventing.AzureServiceBus dotnet add package OpinionatedEventing.RabbitMQ ``` For sagas add: ``` dotnet add package OpinionatedEventing.Sagas ``` For local development with .NET Aspire: ``` dotnet add package OpinionatedEventing.Aspire ``` ## 2. Define your messages Messages are plain C# records. Implement `IEvent` for domain / integration events and `ICommand` for commands. ```csharp using OpinionatedEventing; // An event is something that happened — broadcast to all interested parties. public record OrderPlaced(Guid OrderId, decimal Total) : IEvent; // A command is an instruction directed at one specific handler. public record ProcessPayment(Guid OrderId, decimal Amount) : ICommand; ``` See [Commands vs Events](https://opinionated-eventing.com/docs/commands-vs-events.md) for guidance on when to use each. ## 3. Implement handlers ```csharp using OpinionatedEventing; // Multiple handlers can subscribe to the same event. public class OrderNotificationHandler : IEventHandler { public Task HandleAsync(OrderPlaced @event, CancellationToken cancellationToken) { Console.WriteLine($"Order {@event.OrderId} placed for {@event.Total:C}"); return Task.CompletedTask; } } // Exactly one handler per command type — enforced at startup. public class PaymentCommandHandler : ICommandHandler { public Task HandleAsync(ProcessPayment command, CancellationToken cancellationToken) { Console.WriteLine($"Processing payment of {command.Amount:C} for order {command.OrderId}"); return Task.CompletedTask; } } ``` ## 4. Configure your DbContext (publishing services only) Skip this step if your service only handles messages and never publishes. Add `OutboxMessage` to your `DbContext` and wire up the `DomainEventInterceptor`. ```csharp using Microsoft.EntityFrameworkCore; using OpinionatedEventing.EntityFramework; public class AppDbContext(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyOutboxConfiguration(Database.ProviderName); // outbox_messages table — pass ProviderName for correct SQLite DDL modelBuilder.ApplySagaStateConfiguration(Database.ProviderName); // saga_states table (if using sagas) } } ``` Generate and apply an EF migration: ```bash dotnet ef migrations add AddOutbox dotnet ef database update ``` ## 5. Register services Wire everything up in `Program.cs` (or `Startup.cs`). ```csharp using OpinionatedEventing; using OpinionatedEventing.EntityFramework; // --- Core --- var builder = services .AddOpinionatedEventing() .AddHandlersFromAssemblies(Assembly.GetExecutingAssembly()) .AddOutbox(); // --- EF Core outbox store --- services.AddDbContext((sp, options) => { options.UseSqlServer(connectionString); options.AddInterceptors(sp.GetRequiredService()); }); services.AddOpinionatedEventingEntityFramework(); // --- Transport (choose one) --- // Azure Service Bus: services.AddAzureServiceBusTransport(options => { options.ConnectionString = builder.Configuration["AzureServiceBus:ConnectionString"]; options.ServiceName = "order-service"; // becomes the subscription name }); // RabbitMQ: services.AddRabbitMQTransport(options => { options.ConnectionString = builder.Configuration["RabbitMQ:ConnectionString"]; options.ServiceName = "order-service"; }); ``` You only need one transport — swap them by changing DI registration. No handler code changes required. ## 6. Publish your first event Inject `IPublisher` wherever you need to emit events or send commands. ```csharp public class OrderService(IPublisher publisher, AppDbContext db) { public async Task PlaceOrderAsync(decimal total, CancellationToken ct) { var order = new Order { Total = total }; db.Orders.Add(order); // Write the event to the outbox within the same transaction. await publisher.PublishEventAsync(new OrderPlaced(order.Id, total), ct); // One SaveChanges call commits both the Order row and the outbox row atomically. await db.SaveChangesAsync(ct); } } ``` The `OutboxDispatcherWorker` background service picks up the pending message and forwards it to the broker. Your `OrderNotificationHandler` is called on the consumer side. > **Why not publish directly to the broker?** The outbox pattern guarantees that a message is never lost even if the broker is temporarily unavailable. See [Outbox Pattern](https://opinionated-eventing.com/docs/outbox-pattern.md) for details. ## 7. (Optional) Configure the outbox dispatcher Tune polling and retry behaviour via `OpinionatedEventingOptions`: ```csharp services.AddOpinionatedEventing(options => { options.Outbox.PollInterval = TimeSpan.FromSeconds(2); options.Outbox.BatchSize = 100; options.Outbox.MaxAttempts = 5; options.Outbox.ConcurrentWorkers = 2; }); ``` ## Next steps | Topic | Guide | |---|---| | When to use events vs commands | [Commands vs Events](https://opinionated-eventing.com/docs/commands-vs-events.md) | | How the outbox works internally | [Outbox Pattern](https://opinionated-eventing.com/docs/outbox-pattern.md) | | Long-running workflows | [Saga Orchestration](https://opinionated-eventing.com/docs/sagas-orchestration.md) | | Lightweight event-driven choreography | [Saga Choreography](https://opinionated-eventing.com/docs/sagas-choreography.md) | | Aggregates and domain events | [DDD Aggregates](https://opinionated-eventing.com/docs/ddd-aggregates.md) | | Local dev with Aspire | [Local Development](https://opinionated-eventing.com/docs/local-development.md) | | Logging, tracing, and metrics | [Observability](https://opinionated-eventing.com/docs/observability.md) | --- Source: https://opinionated-eventing.com/docs/commands-vs-events # Commands vs Events OpinionatedEventing makes a strict distinction between commands and events. Understanding the difference is the first step to designing a well-structured message-driven system. ## The core difference | | Command | Event | |---|---|---| | **Marker interface** | `ICommand` | `IEvent` | | **Intent** | "Please do X" | "X happened" | | **Handlers** | Exactly one | Zero or more | | **Broker topology** | Point-to-point (queue) | Publish-subscribe (topic / exchange) | | **Direction** | Sender → specific service | Sender → any interested party | ## Events An event records something that already happened. It is a fact — immutable and past tense. ```csharp public record OrderPlaced(Guid OrderId, decimal Total) : IEvent; public record PaymentReceived(Guid OrderId, Guid PaymentId) : IEvent; public record StockReserved(Guid OrderId, string Sku, int Quantity) : IEvent; ``` Events are broadcast to a topic (Azure Service Bus) or exchange (RabbitMQ). Every service that has registered an `IEventHandler` for that event type receives a copy. If no handler exists, the message is silently discarded — events have no required audience. ```csharp // Multiple handlers can react to the same event. public class NotificationHandler : IEventHandler { ... } public class AuditHandler : IEventHandler { ... } public class OrderSaga : IEventHandler { ... } // started by the saga engine ``` **Use an event when:** - Something happened in your domain that other parts of the system may care about - You want to decouple the producer from its consumers - Multiple downstream systems need to react independently - You cannot predict which services will be interested in the future ## Commands A command is a request to perform a specific action. It has intent and a named target. ```csharp public record ProcessPayment(Guid OrderId, decimal Amount) : ICommand; public record ReserveStock(Guid OrderId, string Sku, int Quantity) : ICommand; public record CancelPayment(Guid OrderId, string Reason) : ICommand; ``` Commands are routed to a single queue and consumed by exactly one handler. The framework enforces this at startup — registering two `ICommandHandler` implementations throws an `InvalidOperationException`. ```csharp // Only one handler allowed per command type. public class PaymentCommandHandler : ICommandHandler { ... } ``` **Use a command when:** - You need a specific service to perform a specific action - You need clear ownership — one service is responsible for executing the operation - You are inside a saga and orchestrating a workflow ## Why the strict separation matters ### Topology maps to intent Events use publish-subscribe topology: one producer, many consumers. Commands use point-to-point topology: one sender, one receiver. Using the wrong abstraction for the wrong intent leads to subtle bugs: - Sending a "command" as an event means you cannot guarantee it is handled by exactly one consumer - Publishing a "state change" as a command means only one service ever learns about it The compiler enforces the distinction through `IEvent` and `ICommand` marker interfaces. The framework maps each to the correct broker topology automatically. ### Decoupling Events give the producing service freedom — it does not need to know who cares. Consumers can be added or removed without touching the producer. Commands do the opposite: the sender explicitly names the recipient service via the queue name, which is intentional for directed operations. ### Causation chain Both events and commands carry `CorrelationId` (the ID of the originating request) and `CausationId` (the ID of the message that caused this one to be sent). This lets you reconstruct the full chain of events and commands across services in traces and logs. ## Naming conventions Use **past-tense verbs** for events, **imperative verbs** for commands: | Good event names | Good command names | |---|---| | `OrderPlaced` | `ProcessPayment` | | `PaymentReceived` | `ReserveStock` | | `StockReserved` | `SendConfirmationEmail` | | `OrderShipped` | `CancelOrder` | Avoid generic names like `OrderUpdated` or `DoSomething`. The name should communicate precisely what happened or what is being requested. ## Naming the broker resources By convention the framework derives broker resource names from the message type name: | Type | Derived name | |---|---| | `OrderPlaced` (event) | topic/exchange: `order-placed` | | `ProcessPayment` (command) | queue: `process-payment` | Override the default with `[MessageTopic]` or `[MessageQueue]` attributes: ```csharp [MessageTopic("payments.events.order-placed")] public record OrderPlaced(Guid OrderId, decimal Total) : IEvent; [MessageQueue("payments.commands.process-payment")] public record ProcessPayment(Guid OrderId, decimal Amount) : ICommand; ``` ## Publishing Both events and commands are published through `IPublisher`. The interface is the same; the routing is different. ```csharp // Fan-out to all IEventHandler registrations. await publisher.PublishEventAsync(new OrderPlaced(order.Id, total), ct); // Point-to-point to the single ICommandHandler. await publisher.SendCommandAsync(new ProcessPayment(order.Id, total), ct); ``` Both calls write to the outbox within the caller's transaction — the actual broker delivery happens asynchronously. See [Outbox Pattern](https://opinionated-eventing.com/docs/outbox-pattern.md) for details. --- Source: https://opinionated-eventing.com/docs/outbox-pattern # Outbox Pattern The outbox pattern guarantees that every message your application writes is eventually delivered to the broker — even if the broker is temporarily unavailable when your code runs. ## The problem it solves Without the outbox, a typical event-publishing flow looks like this: ``` 1. Insert Order row into database 2. Publish OrderPlaced event to broker 3. Commit database transaction ``` This has a critical flaw: steps 1–3 are not atomic. If the broker call in step 2 fails, the Order is saved but no event is published. If the process crashes after step 2 but before step 3, the event is published but the Order is not saved. Either way your data and your messages are out of sync. ## How the outbox solves it The outbox replaces the direct broker call with a write to an `outbox_messages` table in the same database transaction as your business data: ``` 1. Insert Order row into database 2. Insert OutboxMessage row into outbox_messages 3. Commit database transaction ← both rows commit or neither does ``` A background `OutboxDispatcherWorker` then reads the pending rows and forwards them to the broker: ``` 4. Worker reads pending OutboxMessage rows 5. Calls ITransport.SendAsync() for each message 6. On success: marks message ProcessedAt (delivered) 7. On failure: increments AttemptCount, retries up to MaxAttempts 8. After MaxAttempts: marks message FailedAt (dead-letter) ``` Steps 4–8 can be retried indefinitely. The broker call is idempotent from the outbox's perspective — if the process crashes between step 5 and 6, the worker simply picks up the same row again on the next poll. ## There is no direct publish path `IPublisher` writes **only** to the outbox. There is intentionally no method to publish directly to the broker. This design choice means: - You never accidentally bypass the transactional guarantee - The outbox is always the source of truth for what needs to be sent - The broker being slow, unavailable, or restarted does not affect your write path ## Atomic writes with EF Core When you use `OpinionatedEventing.EntityFramework`, the outbox write is fully automatic for domain events raised on aggregate roots. The `DomainEventInterceptor` hooks `DbContext.SaveChangesAsync()` and harvests any `IEvent` instances queued on your aggregates: ```csharp // Inside your aggregate: public void Place(decimal total) { Total = total; Status = OrderStatus.Placed; RaiseDomainEvent(new OrderPlaced(Id, total)); // queued, not written yet } // In your application code: db.Orders.Add(order); order.Place(total); await db.SaveChangesAsync(ct); // ↑ DomainEventInterceptor fires here, harvests OrderPlaced, // creates OutboxMessage, writes both rows in one transaction. ``` If you need to publish an event from application code (not from an aggregate), inject `IPublisher`: ```csharp await publisher.PublishEventAsync(new OrderPlaced(orderId, total), ct); await db.SaveChangesAsync(ct); // commits both the business row and the outbox row ``` ## OutboxMessage structure Each row in `outbox_messages` contains: | Column | Purpose | |---|---| | `Id` | Unique message identifier (Guid) | | `MessageType` | Assembly-qualified CLR type name for deserialization | | `Payload` | JSON-serialized message body | | `MessageKind` | `"Event"` or `"Command"` | | `CorrelationId` | Chain identifier propagated from the originating request | | `CausationId` | ID of the message that caused this one to be published | | `CreatedAt` | When the row was written | | `ProcessedAt` | Set when successfully dispatched to the broker | | `FailedAt` | Set when MaxAttempts is exhausted (dead-lettered) | | `AttemptCount` | Number of dispatch attempts made | | `Error` | Last dispatch error message | | `NextAttemptAt` | Earliest time this message is eligible for retry (backoff) | ## Retry behaviour and exponential backoff The `OutboxDispatcherWorker` retries failed dispatches up to `OutboxOptions.MaxAttempts` (default: 5). After each transient failure, the worker applies exponential backoff: the message is held back until `now + min(2^n seconds, MaxRetryDelay)` where `n` is the new attempt count. The default `MaxRetryDelay` is 5 minutes. | Attempt | Backoff delay | |---|---| | 1st retry | 2 s | | 2nd retry | 4 s | | 3rd retry | 8 s | | 4th retry | 16 s | | 5th retry+ | capped at `MaxRetryDelay` (default 5 min) | This prevents a single poisonous message from hammering the broker at the poll rate. `GetPendingAsync` filters `WHERE NextAttemptAt IS NULL OR NextAttemptAt <= now` so delayed messages are invisible to other workers until their backoff window has elapsed. After `MaxAttempts` failures the row is marked as dead-lettered (`FailedAt` is set). Dead-lettered rows are never retried automatically. Use `IOutboxMonitor.GetDeadLetterCountAsync()` to detect accumulation and alert on it. ## Retention and cleanup By default, processed rows are deleted after 7 days and dead-lettered rows are kept indefinitely. The `OutboxCleanupWorker` hosted service runs hourly and enforces these limits. **Why keep dead-letters indefinitely by default?** Dead-letters represent messages that could not be delivered after all attempts. They are rare and operationally significant — you typically want to inspect them before removing. Configure retention in `OutboxOptions`: ```csharp services.AddOpinionatedEventing(options => { options.Outbox.ProcessedRetention = TimeSpan.FromDays(7); // null = keep forever options.Outbox.FailedRetention = null; // null = keep forever (default) options.Outbox.CleanupInterval = TimeSpan.FromHours(1); // how often the cleanup worker runs }); ``` The cleanup worker is safe to run across multiple application instances. The delete predicates (`ProcessedAt < cutoff` / `FailedAt < cutoff`) are mutually exclusive with the dispatcher's pending-message predicate (`ProcessedAt IS NULL AND FailedAt IS NULL`), so cleanup can never remove a row that the dispatcher is currently processing. Concurrent cleanup runs on the same rows are idempotent. ## Configuring the dispatcher ```csharp services.AddOpinionatedEventing(options => { options.Outbox.PollInterval = TimeSpan.FromSeconds(1); // how often to poll options.Outbox.BatchSize = 50; // messages per poll cycle options.Outbox.MaxAttempts = 5; // before dead-lettering options.Outbox.ConcurrentWorkers = 1; // parallel dispatch workers options.Outbox.MaxRetryDelay = TimeSpan.FromMinutes(5); // backoff cap options.Outbox.ProcessedRetention = TimeSpan.FromDays(7); // null to keep forever options.Outbox.FailedRetention = null; // null to keep forever options.Outbox.CleanupInterval = TimeSpan.FromHours(1); // cleanup sweep interval }); ``` Increase `ConcurrentWorkers` to raise throughput. Each worker polls and dispatches independently. The `IOutboxStore` implementation is responsible for ensuring that concurrent workers do not pick up the same message. The EF Core store uses a claim-column approach: candidate rows are identified with a `SELECT`, then stamped with a unique `LockedBy` token via an `UPDATE` that re-checks the lock predicate. Only rows successfully stamped with that call's token are returned, so concurrent workers cannot receive the same message even without database-level row locking. ## IOutboxStore `IOutboxStore` is an abstraction — implementations live in separate packages. The framework ships two: | Implementation | Package | Purpose | |---|---|---| | `EFCoreOutboxStore` | `OpinionatedEventing.EntityFramework` | Production use | | `InMemoryOutboxStore` | `OpinionatedEventing.Testing` | Unit and integration tests | You can implement `IOutboxStore` yourself to support other persistence backends. ## Health monitoring Use `IOutboxMonitor` to observe the backlog: ```csharp public class OutboxHealthEndpoint(IOutboxMonitor monitor) { public async Task GetPendingCountAsync(CancellationToken ct) => await monitor.GetPendingCountAsync(ct); public async Task GetDeadLetterCountAsync(CancellationToken ct) => await monitor.GetDeadLetterCountAsync(ct); } ``` Or use the built-in health check extension (from `OpinionatedEventing.Aspire`): ```csharp services.AddHealthChecks() .AddOpinionatedEventingHealthChecks(options => { options.OutboxBacklogThreshold = 100; // Degraded above this }); ``` ## Delivery guarantees and consumer idempotency The outbox guarantees **at-least-once delivery** — under certain failure conditions the same message may be delivered more than once. Consumers are responsible for handling duplicates. See [Idempotency](https://opinionated-eventing.com/docs/idempotency.md) for strategies and code examples. ## EF Core migration helpers There are two ways to create the outbox table — **pick one per project and do not mix them**: - **Model-based migrations** — call `modelBuilder.ApplyOutboxConfiguration()` in `OnModelCreating` and let EF generate the `CREATE TABLE` migration automatically via `dotnet ef migrations add`. - **Migration helper methods** — call `migrationBuilder.CreateOutboxTable()` inside a hand-authored migration and do **not** call `ApplyOutboxConfiguration()`. If you do both, EF will generate a duplicate `CreateTable` for the same table the next time you run `dotnet ef migrations add`. Rather than writing migration SQL by hand, use the provided extension methods: ```csharp // In your migration's Up() method: migrationBuilder.CreateOutboxTable(); migrationBuilder.CreateSagaStateTable(); // if using sagas // In your migration's Down() method: migrationBuilder.DropOutboxTable(); migrationBuilder.DropSagaStateTable(); ``` If you are upgrading an existing deployment (the table already exists), add a new migration that applies only the incremental schema change: ```csharp // In the Up() method of a new migration: migrationBuilder.AddOutboxRetentionColumns(); // In the Down() method: migrationBuilder.DropOutboxRetentionColumns(); ``` This adds the `NextAttemptAt` column and the `IX_outbox_messages_cleanup_failed` index. New deployments that call `CreateOutboxTable` already include these elements. --- Source: https://opinionated-eventing.com/docs/sagas-orchestration # Saga Orchestration A saga manages a long-running business process that spans multiple services and messages. The orchestration style uses a central `SagaOrchestrator` that explicitly coordinates each step — sending commands, reacting to events, handling timeouts, and compensating on failure. ## When to use orchestration Use orchestration when: - The workflow has a clear sequence of steps with explicit dependencies - You need timeout and compensation logic (rollback on failure) - You want a single class that makes the full flow readable - The number of participating services is known upfront For looser coupling where each service reacts to events independently, see [Saga Choreography](https://opinionated-eventing.com/docs/sagas-choreography.md). ## Defining a saga Create a POCO state class and an orchestrator: ```csharp // The state is serialized to JSON and persisted between steps. public class OrderSagaState { public Guid OrderId { get; set; } public Guid? PaymentId { get; set; } public bool PaymentConfirmed { get; set; } public bool StockReserved { get; set; } } public class OrderSaga : SagaOrchestrator { protected override void Configure(ISagaBuilder builder) { builder .StartWith(async (evt, state, ctx) => { state.OrderId = evt.OrderId; await ctx.SendCommandAsync(new ProcessPayment(evt.OrderId, evt.Total)); }) .Then(async (evt, state, ctx) => { state.PaymentId = evt.PaymentId; state.PaymentConfirmed = true; await ctx.SendCommandAsync(new ReserveStock(state.OrderId, evt.Sku, evt.Quantity)); }) .Then((evt, state, ctx) => { state.StockReserved = true; ctx.Complete(); // saga is done return Task.CompletedTask; }) .CompensateWith(async (evt, state, ctx) => { // Undo previous steps — run in reverse registration order. await ctx.SendCommandAsync(new CancelPayment(state.OrderId, evt.Reason)); }) .ExpireAfter(TimeSpan.FromMinutes(30)) .OnTimeout(async (state, ctx) => { await ctx.SendCommandAsync(new CancelPayment(state.OrderId, "Timed out")); }); } } ``` ## Registering the saga ```csharp services.AddOpinionatedEventingSagas(); services.AddSaga(); ``` `AddSaga` discovers the event types handled by the orchestrator and automatically registers `IEventHandler` for each one. No manual adapter registration is needed. ## How it works ### Starting a saga When the framework receives an event registered with `StartWith`, it: 1. Creates a new `OrderSagaState` instance 2. Persists a `SagaState` row with `Status = Active` 3. Invokes the `StartWith` handler 4. Saves the updated state The saga's `CorrelationId` is taken from the incoming event's `CorrelationId`. All subsequent commands and events in the chain carry the same `CorrelationId`, which is how the framework correlates them back to the right saga instance. ### Continuing a saga When subsequent events arrive (registered with `Then`), the framework: 1. Looks up the existing `SagaState` by `CorrelationId` 2. Deserializes the persisted `State` JSON back into `TSagaState` 3. Invokes the handler 4. Serializes the updated state and persists it ### Completing a saga Call `ctx.Complete()` inside any handler to mark the saga as `Completed`. No further events will be processed for this instance. ### ISagaContext The `ISagaContext` passed to every handler provides: ```csharp public interface ISagaContext { Guid CorrelationId { get; } Task SendCommandAsync(TCommand command, CancellationToken ct = default) where TCommand : ICommand; Task PublishEventAsync(TEvent @event, CancellationToken ct = default) where TEvent : IEvent; void Complete(); } ``` All messages sent through `ISagaContext` go through the outbox — they are written atomically with the saga state update. ## Timeout and compensation ### Setting a timeout ```csharp builder.ExpireAfter(TimeSpan.FromMinutes(30)); // or — inject TimeProvider so the clock is controllable in tests builder.ExpireAt(timeProvider.GetUtcNow().AddDays(1)); ``` The `SagaTimeoutWorker` background service polls at `SagaOptions.TimeoutCheckInterval` (default: 30 seconds) for sagas whose `ExpiresAt` is in the past and `Status` is still `Active`. It then invokes the `OnTimeout` handler. ### Compensation Register compensation handlers with `CompensateWith`: ```csharp builder.CompensateWith(async (evt, state, ctx) => { await ctx.SendCommandAsync(new CancelPayment(state.OrderId, evt.Reason)); }); ``` When a compensation event arrives, the framework transitions the saga to `Compensating` and runs the handler. Compensation handlers run in **reverse registration order** — last registered, first executed — so you can undo steps in the correct sequence. After compensation completes successfully, the saga transitions to `Completed`. On failure during compensation, it transitions to `Failed`. ## Saga status lifecycle ``` Active ├── ctx.Complete() ──────────────────────→ Completed ├── CompensateWith handler invoked ──→ Compensating │ ├── success ───────────────────────→ Completed │ └── failure ───────────────────────→ Failed └── ExpiresAt reached ───────────────────→ TimedOut └── OnTimeout handler runs └── compensation if needed ──→ Completed / Failed ``` ## Custom correlation By default the framework correlates events to sagas via the `CorrelationId` in the message envelope. If you need to correlate by a property in the event payload, use `CorrelateBy`: ```csharp builder.CorrelateBy(evt => evt.OrderId.ToString()); ``` ## Persisting state: EF Core Saga state is stored in the `saga_states` table. Configure it in your `DbContext`: ```csharp protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.ApplySagaStateConfiguration(); } ``` And register the EF Core store: ```csharp services.AddOpinionatedEventingEntityFramework(); ``` ## Full registration example ```csharp // Add the saga engine services.AddOpinionatedEventingSagas(options => { options.TimeoutCheckInterval = TimeSpan.FromSeconds(30); }); // Register each orchestrator services.AddSaga(); // Register any choreography participants (see sagas-choreography.md) services.AddSagaParticipant(); ``` ## Testing sagas Use `InMemorySagaStateStore` from `OpinionatedEventing.Testing` to test saga logic without a database: ```csharp var store = new InMemorySagaStateStore(); services.AddSingleton(store); // Publish the starting event and assert on store.States ``` Use `FakeTimeProvider` to control the clock when testing timeout behaviour: ```csharp var clock = new FakeTimeProvider(); services.AddSingleton(clock); clock.Advance(TimeSpan.FromMinutes(31)); // trigger timeout ``` --- Source: https://opinionated-eventing.com/docs/sagas-choreography # Saga Choreography Choreography is the lighter-weight alternative to orchestration. Instead of a central coordinator that sends commands and waits for responses, each service independently reacts to the events it cares about — no central workflow class, no shared state machine. `ISagaParticipant` is the building block for choreography in OpinionatedEventing. ## When to use choreography Use choreography when: - Each step is genuinely independent — the services do not need to share state - You want maximum decoupling: adding a new service is a matter of subscribing to an existing event - The workflow has no meaningful timeout or compensation requirements - The flow is simple enough to reason about without a central view Use [orchestration](https://opinionated-eventing.com/docs/sagas-orchestration.md) when you need state, timeouts, compensation, or a single place to read the full workflow. ## ISagaParticipant vs IEventHandler Both `ISagaParticipant` and `IEventHandler` react to events. The difference is context: | | `IEventHandler` | `ISagaParticipant` | |---|---|---| | Access to `ISagaContext` | No | Yes | | Can send commands via outbox | Via `IPublisher` injection | Via `ctx.SendCommandAsync()` | | Can publish events via outbox | Via `IPublisher` injection | Via `ctx.PublishEventAsync()` | | Has CorrelationId from chain | Via `IMessagingContext` | Via `ctx.CorrelationId` | Use `ISagaParticipant` when you need to send commands or publish events as part of a choreographed flow. Use `IEventHandler` for side-effects that don't produce outbound messages. ## Implementing a participant ```csharp public class FulfillmentParticipant : ISagaParticipant { private readonly IInventoryService _inventory; public FulfillmentParticipant(IInventoryService inventory) { _inventory = inventory; } public async Task HandleAsync( PaymentReceived @event, ISagaContext ctx, CancellationToken cancellationToken) { // Reserve stock in response to a payment being received. var result = await _inventory.TryReserveAsync(@event.Sku, @event.Quantity, cancellationToken); if (result.Success) { await ctx.PublishEventAsync( new StockReserved(ctx.CorrelationId, @event.Sku, result.ReservedQuantity), cancellationToken); } else { await ctx.PublishEventAsync( new StockReservationFailed(ctx.CorrelationId, @event.Sku, result.Reason), cancellationToken); } } } ``` ## Registering a participant ```csharp services.AddOpinionatedEventingSagas(); services.AddSagaParticipant(); ``` `AddSagaParticipant` scans the `ISagaParticipant` interface, extracts the event type, registers the correct `IEventHandler` subscription automatically, and wires it to the saga dispatcher. The participant is resolved from DI per message — constructor injection works normally. ## ISagaContext in choreography The `ISagaContext` available in `HandleAsync` provides: ```csharp public interface ISagaContext { Guid CorrelationId { get; } // propagated from the incoming event Task SendCommandAsync(TCommand command, CancellationToken ct = default) where TCommand : ICommand; Task PublishEventAsync(TEvent @event, CancellationToken ct = default) where TEvent : IEvent; void Complete(); // no-op in a stateless participant, but available } ``` All messages sent through `ISagaContext` go through the outbox. If the handler throws, none of them are dispatched. ## Choreography vs orchestration: a comparison Consider the e-commerce flow: ``` OrderPlaced └── FulfillmentParticipant reacts → sends ReserveStock command └── ReserveStock handled → raises StockReserved └── NotificationHandler reacts → sends email ``` With orchestration an `OrderSaga` drives every step and persists state between them. With choreography each service reacts in isolation — there is no saga state table and no coordinator. The choreography version is simpler to write and deploy, but harder to debug across services because there is no single place that holds the full picture of "where is this order in the flow?" **Rule of thumb:** start with choreography. Introduce orchestration when you need compensation, timeout, or a single audit trail. ## Testing participants `ISagaParticipant.HandleAsync` receives an `ISagaContext`. Use `FakeSagaContext` from `OpinionatedEventing.Testing` to assert on sent commands and published events without any broker interaction: ```csharp using OpinionatedEventing.Testing; var ctx = new FakeSagaContext { CorrelationId = Guid.NewGuid() }; var participant = new FulfillmentParticipant(new FakeInventoryService()); await participant.HandleAsync( new PaymentReceived(orderId, paymentId, "SKU-123", 2), ctx, CancellationToken.None); Assert.Single(ctx.PublishedEvents.OfType()); Assert.False(ctx.IsCompleted); // Complete() was not called ``` `FakeSagaContext` captures commands and events in `SentCommands` and `PublishedEvents` (both `IReadOnlyList`). Use `.OfType()` to filter by type, consistent with `FakePublisher`. --- Source: https://opinionated-eventing.com/docs/ddd-aggregates # DDD Aggregates OpinionatedEventing provides first-class support for the Domain-Driven Design (DDD) pattern of aggregate roots that raise domain events. Domain events are written to the outbox automatically, within the same EF Core `SaveChanges` transaction as the aggregate itself. ## Defining an aggregate root Extend `AggregateRoot` and call `RaiseDomainEvent` inside your domain methods: ```csharp using OpinionatedEventing; public class Order : AggregateRoot { public Guid Id { get; private set; } public decimal Total { get; private set; } public OrderStatus Status { get; private set; } private Order() { } // EF Core needs a parameterless constructor public static Order Create(decimal total) { var order = new Order { Id = Guid.NewGuid(), Total = total, Status = OrderStatus.Pending }; order.RaiseDomainEvent(new OrderPlaced(order.Id, total)); return order; } public void Cancel(string reason) { if (Status == OrderStatus.Shipped) throw new InvalidOperationException("Cannot cancel a shipped order."); Status = OrderStatus.Cancelled; RaiseDomainEvent(new OrderCancelled(Id, reason)); } } ``` ## Rules for aggregates **Do call `RaiseDomainEvent` when state changes.** Every meaningful state transition should produce an event that describes what happened. **Do not inject `IPublisher` into aggregates.** Aggregates must not know about infrastructure. `RaiseDomainEvent` queues the event in memory — the `DomainEventInterceptor` writes it to the outbox. **Do not call `SaveChanges` inside aggregate methods.** Persistence is the application layer's concern. **Do keep aggregates pure.** Aggregate methods should change state and raise events — nothing else. No database calls, no HTTP calls, no `async`. ## How domain events reach the outbox When you call `db.SaveChangesAsync()`, the `DomainEventInterceptor` fires before EF writes to the database: 1. It scans `DbContext.ChangeTracker` for tracked entities that implement `IAggregateRoot` 2. For each aggregate with pending domain events, it creates an `OutboxMessage` per event 3. It adds those `OutboxMessage` rows to the change tracker 4. It calls `aggregate.ClearDomainEvents()` so events are not re-harvested on the next save 5. EF writes both the aggregate rows and the outbox rows in a single transaction The entire process is invisible to application code. You write: ```csharp var order = Order.Create(total); db.Orders.Add(order); await db.SaveChangesAsync(ct); // ↑ Order row + OutboxMessage(OrderPlaced) committed atomically ``` ## Wiring up the interceptor Register the interceptor when configuring your `DbContext`: ```csharp services.AddDbContext((sp, options) => { options.UseSqlServer(connectionString); options.AddInterceptors(sp.GetRequiredService()); }); services.AddOpinionatedEventingEntityFramework(); ``` The `DomainEventInterceptor` is registered as scoped by `AddOpinionatedEventingEntityFramework`. ## Correlation propagation Every domain event written to the outbox carries: - `CorrelationId` — taken from `IMessagingContext.CorrelationId` in the current scope, which is the correlation ID of the inbound message being processed (or a new root ID if initiated from an HTTP request) - `CausationId` — taken from `IMessagingContext.CausationId`, linking this event to the message that triggered the current handler This means the full causal chain is captured in the outbox rows and propagated through the broker to consumers. ## AggregateRoot API ```csharp public abstract class AggregateRoot : IAggregateRoot { // Queued domain events, cleared after each SaveChanges. public IReadOnlyList DomainEvents { get; } // Call inside domain methods to queue a domain event. protected void RaiseDomainEvent(IEvent domainEvent); } ``` `ClearDomainEvents()` is internal — only the framework calls it. Application code should never clear the events list. ## Using IAggregateRoot without the base class If your aggregate already extends another base class, implement `IAggregateRoot` directly: ```csharp public interface IAggregateRoot { IReadOnlyList DomainEvents { get; } internal void ClearDomainEvents(); } ``` Because `ClearDomainEvents` is `internal`, you will need to provide your own implementation of the domain events list. Consider using the `AggregateRoot` base class whenever possible. ## Multiple aggregates in one transaction The interceptor scans **all** tracked aggregates. If a single `SaveChanges` modifies multiple aggregates, all their domain events are harvested and written to the outbox atomically: ```csharp db.Orders.Add(order); // raises OrderPlaced db.Invoices.Add(invoice); // raises InvoiceCreated await db.SaveChangesAsync(ct); // Both OutboxMessage rows committed with both entity rows. ``` ## Testing aggregates Test aggregate logic without a database by inspecting `DomainEvents` directly: ```csharp var order = Order.Create(100m); Assert.Single(order.DomainEvents); var evt = Assert.IsType(order.DomainEvents[0]); Assert.Equal(100m, evt.Total); ``` For end-to-end tests that include outbox writes, use `InMemoryOutboxStore`: ```csharp services.AddSingleton(); // After SaveChanges: var store = sp.GetRequiredService(); Assert.Single(store.PendingMessages); ``` --- Source: https://opinionated-eventing.com/docs/local-development # Local Development OpinionatedEventing is designed to run locally without any cloud accounts. The `OpinionatedEventing.Aspire` package provides Aspire AppHost extensions that spin up RabbitMQ or the Azure Service Bus emulator as Docker containers, with zero configuration required. ## Prerequisites - **.NET 11 SDK** — required to build the repository and the Aspire AppHost. Service projects can target .NET 10 or later. - **A container runtime** — Docker Desktop, Podman, or Rancher Desktop. > **Note:** Current versions of Aspire no longer need the separate `dotnet workload install aspire` step. Aspire is now a set of NuGet packages; there is no workload to install. See [aspire.dev](https://aspire.dev/get-started/prerequisites/) for the current prerequisites. ## Project structure An Aspire solution typically has at least two projects: ``` YourSolution.AppHost/ ← Aspire host (orchestrates resources) YourSolution.ApiService/ ← Your application service(s) ``` Add the Aspire package to the AppHost: ``` dotnet add package OpinionatedEventing.Aspire ``` ## RabbitMQ ### AppHost setup ```csharp // AppHost/Program.cs using Aspire.Hosting; var builder = DistributedApplication.CreateBuilder(args); var rabbit = builder.AddRabbitMqMessaging("rabbitmq"); var api = builder.AddProject("api") .WithReference(rabbit); builder.Build().Run(); ``` `AddRabbitMqMessaging` starts a RabbitMQ container with the management plugin enabled. It injects a `ConnectionStrings__rabbitmq` environment variable into any project that references it. ### Service setup In your service project, use `AddRabbitMQTransport` and leave `ConnectionString` unset — the transport auto-discovers it from `IConfiguration["ConnectionStrings:rabbitmq"]`: ```csharp services.AddRabbitMQTransport(options => { options.ServiceName = "order-service"; options.AutoDeclareTopology = true; // declare exchanges and queues at startup }); ``` ## Azure Service Bus emulator ### AppHost setup ```csharp // AppHost/Program.cs using Aspire.Hosting; var builder = DistributedApplication.CreateBuilder(args); var asb = builder.AddAzureServiceBusEmulator("servicebus"); var api = builder.AddProject("api") .WithReference(asb); builder.Build().Run(); ``` `AddAzureServiceBusEmulator` starts the Azure Service Bus emulator container and injects its connection string. ### Service setup ```csharp services.AddAzureServiceBusTransport(options => { options.ServiceName = "order-service"; options.AutoCreateResources = true; // create topics and queues at startup }); ``` The transport reads the injected connection string automatically — no manual configuration needed. ## Switching transports Switching between RabbitMQ and Azure Service Bus requires only a DI change. Handler, aggregate, and saga code is identical for both transports. A common pattern is to use `IConfiguration` or environment variables to select the transport: ```csharp if (builder.Configuration["Transport"] == "AzureServiceBus") { services.AddAzureServiceBusTransport(options => { options.ServiceName = "order-service"; options.AutoCreateResources = true; }); } else { services.AddRabbitMQTransport(options => { options.ServiceName = "order-service"; options.AutoDeclareTopology = true; }); } ``` In `appsettings.Development.json`: ```json { "Transport": "RabbitMQ" } ``` ## Running locally To try the included sample (four services, RabbitMQ, PostgreSQL — zero config): ```bash # From the repository root aspire run # Or without the Aspire CLI dotnet run --project samples/Samples.AppHost ``` See [samples/README.md](https://github.com/SierraNL/OpinionatedEventing/blob/main/samples/README.md) for the full walkthrough and how to place a test order. For your own solution: ```bash cd src/YourSolution.AppHost dotnet run ``` The Aspire dashboard opens automatically at `http://localhost:15888`. It shows: - All running services and their health status - Console output per service - Distributed traces (if OTel is configured) - Resource connection strings ## Health checks Both transport packages expose health checks via the `OpinionatedEventing.Aspire` extensions: ```csharp services.AddHealthChecks() .AddOpinionatedEventingHealthChecks(options => { options.OutboxBacklogThreshold = 100; options.SagaTimeoutBacklogThreshold = 10; }); app.MapHealthChecks("/health"); ``` The Aspire dashboard polls `/health` and reflects the status in the resources view. | Health check | Tags | Condition | |---|---|---| | Broker connectivity | `live`, `broker` | Unhealthy if broker is unreachable | | Outbox backlog | `ready`, `outbox` | Degraded above `OutboxBacklogThreshold` | | Saga timeout backlog | `ready`, `saga` | Degraded above `SagaTimeoutBacklogThreshold` | ## RabbitMQ management UI When using `AddRabbitMqMessaging`, the management plugin is enabled. Access the RabbitMQ management UI at: ``` http://localhost:15672 ``` Default credentials: `guest` / `guest` Here you can inspect exchanges, queues, bindings, and message rates in real time. --- Source: https://opinionated-eventing.com/docs/observability # Observability OpinionatedEventing emits structured logs, distributed traces, and metrics out of the box. All telemetry uses standard .NET abstractions — no Serilog, Seq, or OpenTelemetry package is required in the library itself. ## Logging The library uses `Microsoft.Extensions.Logging.ILogger`. As long as you configure a logging provider in your host, log output flows automatically. ### What is logged | Component | Level | Events | |---|---|---| | `OutboxDispatcherWorker` | `Debug` | Poll cycle start/end, batch size | | `OutboxDispatcherWorker` | `Information` | Message dispatched successfully | | `OutboxDispatcherWorker` | `Warning` | Dispatch attempt failed (retrying) | | `OutboxDispatcherWorker` | `Error` | Message dead-lettered after MaxAttempts | | `SagaTimeoutWorker` | `Debug` | Timeout check cycle | | `SagaTimeoutWorker` | `Information` | Saga timed out, timeout handler invoked | | `SagaTimeoutWorker` | `Error` | Timeout handler threw exception | | Transport consumers | `Debug` | Message received | | Transport consumers | `Information` | Message handled successfully | | Transport consumers | `Error` | Handler threw unhandled exception | ### Configuring log levels In `appsettings.json`: ```json { "Logging": { "LogLevel": { "Default": "Information", "OpinionatedEventing": "Debug" } } } ``` ## Distributed tracing The library uses `System.Diagnostics.ActivitySource`. All activity source names are under the `opinionatedeventing` prefix. Wire them up via the OpenTelemetry SDK: ```csharp using OpinionatedEventing.OpenTelemetry; services.AddOpenTelemetry() .WithTracing(tracing => tracing .AddOpinionatedEventingInstrumentation() .AddOtlpExporter()); ``` ### Emitted spans | Span name | When | Key attributes | |---|---|---| | `outbox.write` | `IPublisher` writes to the outbox store | `messaging.message.type`, `messaging.message.kind`, `messaging.message.correlation_id` | | `outbox.dispatch` | `OutboxDispatcherWorker` calls `ITransport.SendAsync` | `messaging.message.id`, `messaging.message.type` | | `consume` | Transport consumer hands off to handler(s) | `messaging.message.type`, `messaging.message.kind`, `messaging.message.correlation_id` | | `saga.step` | A saga handler executes | `saga.type`, `saga.correlation_key`, `messaging.message.type` | Each span carries W3C trace context propagated through the message envelope so traces span service boundaries. ### Viewing traces locally When using Aspire, the dashboard includes a built-in trace viewer. Traces from all services are aggregated automatically — no additional exporter configuration is needed for local development. ## Metrics The library uses `System.Diagnostics.Metrics.Meter`. Wire up the metrics provider: ```csharp using OpinionatedEventing.OpenTelemetry; services.AddOpenTelemetry() .WithMetrics(metrics => metrics .AddOpinionatedEventingMetrics() .AddOtlpExporter()); ``` ### Available instruments | Instrument | Type | Description | |---|---|---| | `opinionatedeventing.outbox.pending` | Gauge | Current number of pending (unprocessed) outbox messages | | `opinionatedeventing.outbox.processed` | Counter | Total messages successfully dispatched to the broker | | `opinionatedeventing.outbox.failed` | Counter | Total messages dead-lettered after MaxAttempts | | `opinionatedeventing.publish.duration` | Histogram | Time (ms) to write a message to the outbox store | | `opinionatedeventing.dispatch.duration` | Histogram | Time (ms) to dispatch a message to the broker | | `opinionatedeventing.consume.duration` | Histogram | Time (ms) for the handler to process a message | | `opinionatedeventing.saga.active` | Gauge | Current number of active saga instances | | `opinionatedeventing.saga.timed_out` | Counter | Total sagas that have timed out | ### Alerting recommendations | Metric | Alert condition | Meaning | |---|---|---| | `opinionatedeventing.outbox.pending` | > threshold for > 5 min | Dispatcher is stalled or the broker is unavailable | | `opinionatedeventing.outbox.failed` | Rate > 0 | Messages are dead-lettering — investigate errors | | `opinionatedeventing.consume.duration` | p99 > SLA | Handler is slow — risk of broker timeout and redelivery | | `opinionatedeventing.saga.active` | Growing without bound | Sagas are not completing — check timeouts | ## Health checks Health checks are the quickest way to surface observability in an operations dashboard: ```csharp services.AddHealthChecks() .AddOpinionatedEventingHealthChecks(options => { options.OutboxBacklogThreshold = 100; // pending messages before Degraded options.SagaTimeoutBacklogThreshold = 10; // expired sagas before Degraded }); app.MapHealthChecks("/health"); app.MapHealthChecks("/health/live", new HealthCheckOptions { Predicate = c => c.Tags.Contains("live") }); app.MapHealthChecks("/health/ready", new HealthCheckOptions { Predicate = c => c.Tags.Contains("ready") }); ``` The built-in checks use two tags: | Tag | Checks | |---|---| | `live` | Broker connectivity | | `ready` | Outbox backlog, saga timeout backlog | Broker connectivity is a liveness check (`live`), not readiness: if the broker is unreachable the process is genuinely broken and a restart may help re-establish the connection. Backlog checks are readiness signals — a load balancer can stop routing HTTP traffic to the instance while the background workers drain the queue. **Readiness and broker consumers:** readiness probes only control the Kubernetes `Service` endpoint, which governs *HTTP* traffic. The broker consumer workers are `BackgroundService` instances that pull messages directly from the broker, independent of any load balancer. By default, a degraded readiness check does **not** pause event consumption. To automatically pause consumers when a dependency becomes unavailable, chain `WithConsumerPause()` and tag the relevant checks with `"pause"`: ```csharp services.AddHealthChecks() .AddOpinionatedEventingHealthChecks() .AddNpgsql(connectionString, tags: ["pause"]) // pause consumers when DB is unreachable .WithConsumerPause(); ``` When any check tagged `"pause"` reports `Degraded` or `Unhealthy`, the consumer workers stop accepting new messages from the broker. They resume automatically once all `"pause"`-tagged checks recover to `Healthy`. This is opt-in — the default behaviour (always consuming) is preserved when `WithConsumerPause()` is not called. The built-in backlog checks (`"ready"`) intentionally do **not** carry the `"pause"` tag. Pausing consumers does not help drain the outbox or saga-timeout backlogs — those are drained by `OutboxDispatcherWorker` and `SagaTimeoutWorker`, which are never paused. Wiring backlog checks to consumer pause would cause oscillation: consumers pause → broker queue grows → backlogs eventually drain → consumers resume → new messages create more backlog → repeat. ## Correlation and causation IDs Every message carries two identifiers that let you reconstruct the full causal chain across services: - **CorrelationId** — Set at the entry point (e.g., an HTTP request ID) and propagated through every event and command in the chain. All spans and log entries include this. - **CausationId** — The `Id` of the message that caused this one to be sent. Null for root messages. This is how you reconstruct the parent-child relationship between messages. These IDs are accessible in handlers via `IMessagingContext`: ```csharp public class OrderNotificationHandler(IMessagingContext context) : IEventHandler { public Task HandleAsync(OrderPlaced @event, CancellationToken ct) { // context.CorrelationId — same across the entire order flow // context.CausationId — ID of the message that triggered this handler return Task.CompletedTask; } } ``` ### Automatic logging scope `MessageHandlerRunner` calls `ILogger.BeginScope` before invoking handlers, pushing `CorrelationId`, `CausationId`, and `MessageType` as structured properties into the ambient logging scope: ```json { "CorrelationId": "3fa85f64-5717-4562-b3fc-2c963f66afa6", "CausationId": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "MessageType": "MyApp.Orders.OrderPlaced, MyApp" } ``` Any `ILogger` used inside a handler automatically inherits these properties — no manual logging required. Logging providers that support structured scopes (OpenTelemetry, Serilog, Application Insights) pick them up and include them on every log entry emitted during handler execution. --- Source: https://opinionated-eventing.com/docs/idempotency # Idempotency The outbox pattern guarantees **at-least-once delivery**: every message written to the outbox will eventually reach the broker, but under certain failure conditions (process crash between dispatch and acknowledgement) a message may be delivered more than once. Consumers must therefore be prepared to receive duplicates. ## Decision: no built-in inbox store OpinionatedEventing does **not** provide an `IInboxStore` abstraction (see [REQUIREMENTS.md § Non-Goals](https://github.com/SierraNL/OpinionatedEventing/blob/main/REQUIREMENTS.md#1-goals--non-goals)). This is a stated v1.0 scope decision, not a gap: - **A shared inbox store would introduce a mandatory persistence dependency** into every consuming service, even when the handler is naturally idempotent or the business risk of a duplicate is low. - **Deduplication only works if it commits in the same transaction as the handler's business logic** — otherwise there's a window where the "already processed" check and the side effect can disagree. `IOutboxStore` can own its own transaction because it's the only writer at that point; a dedup check has to share the *consumer's own* `DbContext` / unit-of-work, which makes a generic, reusable `IInboxStore` a materially harder abstraction to get right than the outbox was. Handing consumers the primitive (`IMessagingContext.MessageId`, below) and letting them dedupe inside their own transaction sidesteps that problem entirely. The patterns below — including using `IMessagingContext.MessageId` as a dedup key — cover the same ground an inbox store would. The decision is re-evaluated after gathering real-world usage data — see [Future versions](#future-versions). ## Why duplicates happen The `OutboxDispatcherWorker` marks a message as processed only after the broker confirms receipt. If the process crashes or restarts after the broker receives the message but before the confirmation is written to the database, the worker will re-dispatch the same row on the next poll cycle. The broker receives the message twice, and both deliveries reach your handlers. ## Strategies for consumer-side idempotency ### 1. Natural idempotency The simplest case: the handler's effect is idempotent by construction. A handler that sets a flag, updates a value to a fixed state, or performs a read-only side effect can safely run twice without harm. Prefer this approach where the domain allows it. ```csharp public class MarkOrderPaidHandler : IEventHandler { public async Task HandleAsync(OrderPaid @event, CancellationToken ct) { // UPDATE ... SET Status = 'Paid' WHERE Id = @id // Running this twice is harmless — the row ends up in the same state. await _db.Orders .Where(o => o.Id == @event.OrderId) .ExecuteUpdateAsync(s => s.SetProperty(o => o.Status, OrderStatus.Paid), ct); } } ``` ### 2. Idempotency key check (manual inbox) Track processed message IDs in a database table. Before executing the handler's business logic, check whether the message ID has already been recorded. If it has, skip the work. Record the ID and commit in the same transaction as the business operation. `IMessagingContext.MessageId` carries the inbound message's own ID — inject `IMessagingContext` into your handler and use it as the deduplication key: ```csharp public class SendWelcomeEmailHandler(IMessagingContext messagingContext, AppDbContext db, IEmailClient emailClient) : IEventHandler { public async Task HandleAsync(UserRegistered @event, CancellationToken ct) { bool alreadyProcessed = await db.ProcessedMessages .AnyAsync(m => m.MessageId == messagingContext.MessageId, ct); if (alreadyProcessed) return; await emailClient.SendWelcomeEmailAsync(@event.Email, ct); db.ProcessedMessages.Add(new ProcessedMessage(messagingContext.MessageId)); await db.SaveChangesAsync(ct); } } ``` Prune the `ProcessedMessages` table periodically — rows older than your message retention window (e.g. 7 days) are safe to delete. ### 3. Conditional insert / unique constraint Use a database unique constraint on the message ID column instead of an explicit `SELECT` before `INSERT`. This avoids the read entirely and lets the database enforce uniqueness. Use `IMessagingContext.MessageId` as the deduplication key (same as strategy 2). ```sql CREATE UNIQUE INDEX ux_processed_messages_id ON processed_messages (message_id); ``` Catch the resulting `DbUpdateException` / unique-constraint violation and treat it as "already processed". The exact inner-exception type is provider-specific (SQL Server throws `SqlException`, PostgreSQL throws `NpgsqlException`), so check the message text or use a provider helper: ```csharp try { _db.ProcessedMessages.Add(new ProcessedMessage(@event.MessageId)); await _db.SaveChangesAsync(ct); } catch (DbUpdateException ex) when ( ex.InnerException?.Message.Contains("unique", StringComparison.OrdinalIgnoreCase) == true) { return; // already processed — duplicate delivery } // execute business logic here — only reached on first delivery await DoWorkAsync(@event, ct); ``` ### 4. Idempotent external calls When the side effect is a call to an external API, pass the message ID as the idempotency key if the API supports it (most payment, email, and notification APIs do). Inject `IMessagingContext` into your handler to access `MessageId`: ```csharp await _paymentGateway.ChargeAsync(new ChargeRequest { IdempotencyKey = _messagingContext.MessageId.ToString(), Amount = @event.Amount, Currency = @event.Currency, }); ``` The API will return the original response for any duplicate call with the same key, and your handler exits cleanly. ## Which strategy to use | Scenario | Recommended strategy | |---|---| | Effect is a state-machine transition or idempotent update | Natural idempotency | | Effect must run exactly once, DB available in handler | Unique-constraint insert | | External API with idempotency-key support | Pass message ID as key | | Multiple side effects that must all-or-nothing deduplicate | Manual inbox with transaction | ## Future versions An `IInboxStore` abstraction (modelled after `IOutboxStore`) with an EF Core implementation is a candidate for a future release. If you need it now, the patterns above cover the same ground with code you control.