GM.Messaging.AspNetCore 4.2.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package GM.Messaging.AspNetCore --version 4.2.0
                    
NuGet\Install-Package GM.Messaging.AspNetCore -Version 4.2.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="GM.Messaging.AspNetCore" Version="4.2.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="GM.Messaging.AspNetCore" Version="4.2.0" />
                    
Directory.Packages.props
<PackageReference Include="GM.Messaging.AspNetCore" />
                    
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 GM.Messaging.AspNetCore --version 4.2.0
                    
#r "nuget: GM.Messaging.AspNetCore, 4.2.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 GM.Messaging.AspNetCore@4.2.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=GM.Messaging.AspNetCore&version=4.2.0
                    
Install as a Cake Addin
#tool nuget:?package=GM.Messaging.AspNetCore&version=4.2.0
                    
Install as a Cake Tool

<p align="center"> <img src="https://raw.githubusercontent.com/gmetskhvarishvili/GM.Messaging/master/icon.png" alt="GM.Messaging" width="140" height="140" /> </p>

GM.Messaging

CI NuGet License: MIT

A lightweight messaging setup for .NET built on Wolverine and RabbitMQ. One call wires up the message bus from configuration — connection, resilience (retry + circuit breaker), and producer/consumer topology — with a transactional outbox/inbox for reliable, integration events that are published at least once and handled once per consumer. Part of the GM.* family of packages. Targets net10.0.

Packages

This repository ships four packages that version and release in lockstep:

Package What it provides
GM.Messaging AddGMMessaging (Wolverine + RabbitMQ wiring, resilience, topology), AddGMOutboxRelay, and the broker tools.
GM.Messaging.Domain IntegrationEvent, [IntegrationEventName], IntegrationEventRegistry, and the InboxMessage / OutboxMessage entities.
GM.Messaging.Persistence EF Core configurations, the transactional inbox (AddGMInbox), the inbox worker (AddGMInboxWorker), payload protection, and telemetry names.
GM.Messaging.AspNetCore MapGMMessagingAdmin(): operations endpoints for the outbox, inbox and broker queues, behind authorization.

The outbox and inbox are tested against PostgreSQL and SQL Server (leasing, concurrent claims and ordering), and SQLite for the unit tests.

Install

dotnet add package GM.Messaging

Register

using GM.Messaging;

builder.Services.AddGMMessaging(builder.Configuration);

Configure

Everything comes from the Messaging configuration section (shape matches MessagingOptions); every value has a sensible default:

{
  "Messaging": {
    "ServiceName": "orders-service",
    "RabbitMq": {
      "HostName": "localhost",
      "Port": 5672,
      "VirtualHost": "/",
      "UserName": "guest",
      "Password": "guest",
      "PublisherConfirms": true,
      "UnroutedExchange": "gm.unrouted",
      "UpgradeExchanges": false
    },
    "Retry": { "MaxAttempts": 5, "InitialDelayMilliseconds": 250 },
    "CircuitBreaker": { "Enabled": true, "FailurePercentageThreshold": 25 },
    "OutboxRelay": {
      "BatchSize": 50,
      "PollingIntervalSeconds": 5,
      "MaxRetries": 5,
      "RetryBaseDelaySeconds": 5,
      "RetryMaxDelaySeconds": 300,
      "LeaseSeconds": 60,
      "RetentionDays": 7,
      "CleanupIntervalMinutes": 60,
      "WakeUpExchange": "gm.outbox.wake-up"
    },
    "Inbox": {
      "RetentionDays": 30,
      "CleanupIntervalMinutes": 60,
      "BatchSize": 50,
      "PollingIntervalSeconds": 5,
      "MaxConcurrency": 10,
      "MaxAttempts": 5,
      "RetryBaseDelaySeconds": 5,
      "RetryMaxDelaySeconds": 300,
      "LeaseSeconds": 60,
      "ConsumerNames": [],
      "ConsumerName": "billing"
    }
  }
}

Connecting to a managed or clustered broker. Instead of HostName … Password, set RabbitMq:Uri (amqps://user:password@host/vhost turns TLS on). RabbitMq:UseTls (with an optional TlsServerName) enables TLS for host-based settings and moves the default port to 5671, and RabbitMq:ClusterNodes (["mq-2", "mq-3:5673"]) lists further nodes to connect or fail over to. Wolverine's transport, the outbox wake-ups and the broker tools all use these settings.

Optional ProducerTopology / ConsumerTopology sections declare exchange/queue routes, and the configureWolverine callback on AddGMMessaging lets you customize Wolverine directly. A route's MessageType can be the event's [IntegrationEventName] (it survives class renames), its full type name, or "Namespace.Type, Assembly":

"ProducerTopology": { "Routes": [ { "MessageType": "orders.order-placed", "Exchange": "orders" } ] }

Publish an integration event

[IntegrationEventName("orders.order-placed")] // optional, see "Event names" below
public record OrderPlaced(Guid OrderId) : IntegrationEvent;

// Save the event in the same transaction as the change that raised it.
dbContext.Add(order);
dbContext.Add(OutboxMessage.From(new OrderPlaced(order.Id)));
await dbContext.SaveChangesAsync();

The outbox relay then publishes it through Wolverine.

Wire the outbox and inbox

Both work directly on your DbContext. Map the tables with OutboxMessageConfiguration<T> and InboxMessageConfiguration<T>, then:

// Producer: publishes the outbox and deletes published messages after RetentionDays
builder.Services.AddGMOutboxRelay<OutboxMessage, AppDbContext>();

// Consumer: a scoped IInboxProcessor, plus deletion of handled rows after RetentionDays
builder.Services.AddGMInbox<InboxMessage, AppDbContext>();

TOutboxMessage / TInboxMessage can be your own subclasses of the base entities; a private parameterless constructor is enough (use Populate(evt) in a derived outbox type's factory).

The outbox relay

  • Published means confirmed. RabbitMQ publisher confirms are on (RabbitMq:PublisherConfirms), so a message is marked published only after the broker has accepted it; a rejected or lost publish throws and is retried.
  • Missing routes fail loudly. An event type with no publish route (not in ProducerTopology:Routes) fails with NoRouteException and is retried, then dead-lettered, instead of being dropped silently.
  • Retries with backoff. A failed publish waits RetryBaseDelaySeconds, doubling each time up to RetryMaxDelaySeconds.
  • Unroutable messages are kept. RabbitMQ drops a message published to an exchange with no matching queue (for example before any consumer has bound one), and still confirms it. GM topology gives every exchange it declares an alternate exchange, gm.unrouted (RabbitMq:UnroutedExchange), so such messages land in the gm.unrouted queue instead of disappearing. Watch that queue (the RabbitMQ UI shows its depth) and move messages back once the consumer's queue exists.
  • Dead-letters. After MaxRetries failures the message gets DeadLetteredAtUtc, is logged at error level, and is no longer tried. Fix the cause, then requeue it through IOutboxAdministration (see "Dead letters and backlog").
  • Keeps order per key. Messages with the same ordering key are published one at a time, in the order they were raised; see "Ordered events".
  • Publishes at once. Add the interceptor to your DbContext and a save that adds outbox messages wakes the relay instead of it waiting for its next poll, in this process directly and in other processes over a small RabbitMQ fanout exchange (OutboxRelay:WakeUpExchange): services.AddDbContext<AppDbContext>((sp, o) => o.UseNpgsql(cs).AddGMOutboxSignal(sp));. In a process that saves outbox messages but doesn't relay (an API), also call services.AddGMOutboxWakeUp(configuration). If RabbitMQ is unreachable, relays simply poll.
  • Runs in several processes. Each message is leased to one relay (LockedBy, LockedUntilUtc) with a compare-and-set update before it is published, so an API and a worker can both run the relay. A message is published twice only if a relay stops mid-publish and its lease (LeaseSeconds) runs out; the consumer's inbox absorbs that.
  • Keeps the table small. Published messages are deleted after RetentionDays (0 keeps them).

The project that calls AddGMOutboxRelay needs the GM.Messaging package, not just GM.Messaging.Persistence. If you'd rather keep the persistence layer on GM.Messaging.Persistence alone, call AddGMOutboxRelay from the host's Program.cs, or pass a flag into your persistence registration (AddPersistence(configuration, runOutboxRelay: true)) to pick which hosts relay.

Handle an event once: ProcessAsync

public static class OrderPlacedHandler
{
    public static Task Handle(OrderPlaced message, IInboxProcessor inbox, AppDbContext db, CancellationToken ct) =>
        inbox.ProcessAsync(message, () =>
        {
            db.Add(Invoice.For(message.OrderId));
            return Task.CompletedTask; // ProcessAsync saves and commits
        }, ct);
}
  • The handler gets the inbox's DbContext. AddGMInbox records the DbContext, and AddGMMessaging has Wolverine take it from the message's scope (its generated code can't build a DbContext itself), so db above is the same instance the inbox uses. No Wolverine setup needed.
  • One transaction. The inbox row and everything the handler saves through the same DbContext commit together. Changes made elsewhere (another database, an HTTP call) aren't covered; a handler that changes nothing through that DbContext is logged once, as a hint.
  • One consumer name per service. Set Messaging:Inbox:ConsumerName (default: the entry assembly's name) and call ProcessAsync(message, handler, ct) / IngestAsync(message, ct) without a name, so a typo can't create a second consumer.
  • Failures are retried. When the handler throws, its changes roll back, the error and attempt count are recorded on the row, and the exception reaches Wolverine, whose retry policy runs the handler again. Only a successful run marks the event handled.
  • Duplicates are skipped, including two deliveries arriving at the same moment: the second waits on the first's row lock and then skips.
  • Inside a transaction you opened yourself, the row joins it and you commit.

Handle it later: IngestAsync and the inbox worker

For work that shouldn't block the consumer (sending email, calling a slow API), store the event and let the inbox worker handle it:

builder.Services.AddGMInboxWorker<InboxMessage, AppDbContext>();
builder.Services.AddGMInboxHandler<UserRegistered, SendWelcomeEmail>();

// In the Wolverine handler:
public Task Handle(UserRegistered message, IInboxProcessor inbox, CancellationToken ct) =>
    inbox.IngestAsync(message, "notifications", ct);

public class SendWelcomeEmail(IEmailSender email) : IInboxHandler<UserRegistered>
{
    public Task HandleAsync(UserRegistered e, CancellationToken ct) => email.SendWelcomeAsync(e.Email, ct);
}

The worker leases rows like the relay (so it can run in several processes), runs up to MaxConcurrency handlers at once, retries failures with backoff, and dead-letters a row after MaxAttempts. InboxMessage.Requeue() makes a dead-lettered row pending again. Set ConsumerNames to handle only some consumers' rows.

Event names

Each row stores the event's name: its [IntegrationEventName] if it has one, otherwise its full type name (namespace and class, without the assembly). Moving an event to another assembly is safe. Renaming the class or its namespace strands rows already written, unless the event keeps its old name through [IntegrationEventName("…")]. Rows written by 1.x (assembly-qualified names) still resolve.

Event versions

Payloads are read leniently (property names case-insensitive, unknown properties ignored), so adding a property is safe. For an incompatible change, raise the event's version and register an upcaster from the previous one; rows still in the outbox or inbox are converted before they're read:

[IntegrationEventName("orders.order-shipped", Version = 2)] // v2 renamed Courier to Carrier
public record OrderShipped(Guid OrderId, string Carrier) : IntegrationEvent;

services.AddGMIntegrationEvents(events => events
    .AddAssembly(typeof(OrderShipped).Assembly)
    .AddUpcaster<OrderShipped>(fromVersion: 1, v1 =>
    {
        v1["Carrier"] = v1["Courier"]?.DeepClone();
        v1.Remove("Courier");
        return v1;
    }));

The version also travels on the wire: GM.Messaging sets Wolverine's serializer to one that sends each event's version in the gm-event-version header, so a consumer already at version 2 upcasts a version-1 event a not-yet-upgraded producer sent. The outbox, the inbox and the wire use the same JSON options (ConfigureJson above). A missing upcaster fails the message (retried, then dead-lettered) with an error naming the step.

By default these settings live in the shared, process-wide IntegrationEventRegistry.Shared. Running the same AddGMIntegrationEvents setup in two hosts of one process, as integration tests often do, is fine; registering a different upcaster for the same step, or different JSON options, throws instead of silently changing how the other host reads events. A host that needs settings of its own gets its own registry, which the relay, the inbox, the inbox worker and the wire serializer then use; it writes outbox rows through it too:

services.AddGMIntegrationEvents(e => e.ConfigureJson(o => o.PropertyNamingPolicy = JsonNamingPolicy.SnakeCaseLower), isolated: true);

// in a command handler, with IntegrationEventRegistry injected
db.Add(OutboxMessage.From(registry, new OrderPlaced(orderId)));

Protecting payloads

Outbox and inbox rows hold the event as JSON. To keep personal data out of the database in clear text, register a protector and add its interceptor to each DbContext; the relay and the inbox worker read protected rows back, and rows written before protection was on stay readable. The broker still carries the plain event, which consumers need.

services.AddGMPayloadDataProtection()                 // ASP.NET Core Data Protection
    .PersistKeysToDbContext<KeysDbContext>();         // keys every instance can reach
services.AddDbContext<AppDbContext>((sp, o) => o.UseNpgsql(cs).UseGMPayloadProtection(sp));

// or your own: services.AddGMPayloadProtection<MyKmsProtector>();  (IMessagePayloadProtector)

Ordered events

Give events an ordering key, by implementing IOrderedIntegrationEvent or with OutboxMessage.From(evt, orderingKey: "order-42"). The relay publishes messages with the same key one at a time in creation order, even across several relays: a message waits until the earlier ones with its key are published or dead-lettered (a dead-lettered message doesn't block its key forever). Keys don't slow each other down. To keep the order on the consumer side, handle the queue sequentially (set "Sequential": true on its ConsumerTopology binding).

Dead letters and backlog

IOutboxAdministration (registered by AddGMOutboxRelay, or AddGMOutboxAdministration in a process without the relay) and IInboxAdministration (registered by AddGMInbox) list dead-lettered messages, requeue one or all, purge them, and report the backlog (pending count, oldest pending, dead-lettered count). The GM.Messaging.AspNetCore package maps all of it, and the broker tools below, as HTTP endpoints for whatever the service registered. They require authorization unless you opt out:

app.MapGMMessagingAdmin(o => o.AuthorizationPolicy = "ops");   // /admin/messaging/outbox, /inbox, /broker/...
// o.AllowAnonymous = true only for local development

The GM.HealthChecks.Messaging package turns the backlog into a health check.

When Wolverine gives up on an integration event and moves it to the error queue, GM also dead-letters its unhandled ProcessAsync inbox rows, so IInboxAdministration lists the failure next to the message in the broker's dead-letter queue. GM's default failure policy does this; add it to failure rules of your own with AndMarkGMInboxDeadLettered():

opts.OnException<TimeoutException>().RetryTimes(2).Then.MoveToErrorQueue().AndMarkGMInboxDeadLettered();

Such rows have RetriedByInboxWorker = false: fix the cause and replay them from the broker (below), which hands them to the handler again. Requeueing in IInboxAdministration applies to ingested rows only.

Messages in RabbitMQ that nothing handled have their own tool, IBrokerQueueAdministration (registered by AddGMMessaging): count and peek a queue, send dead letters (messages a consumer still failed after Wolverine's retries, in ConsumerTopology:DeadLetterQueue) back to the queue they came from, and move unrouted messages (in gm.unrouted) to their exchange once a consumer's queue exists. A BrokerMessageFilter picks messages by type, original queue, routing key, payload text (BodyContains) or age (DeadLetteredBefore), caps how many, and with DryRun only counts; messages it leaves alone stay in the queue in their order. The tool keeps one RabbitMQ connection for all calls.

app.MapGet("/admin/broker/dead-letters", (IBrokerQueueAdministration broker) => broker.PeekAsync("gm.dead-letters"));
app.MapPost("/admin/broker/dead-letters/replay", (IBrokerQueueAdministration broker, string? type, bool dryRun) =>
    broker.ReplayDeadLettersAsync("gm.dead-letters", new BrokerMessageFilter { MessageType = type, DryRun = dryRun }));
app.MapPost("/admin/broker/unrouted/move", (IBrokerQueueAdministration broker) => broker.MoveAsync("gm.unrouted", "gm.events"));

Observability

Add the GM.Messaging source and meter (MessagingTelemetry.Name) to OpenTelemetry:

builder.Services.AddOpenTelemetry()
    .WithTracing(t => t.AddSource(MessagingTelemetry.Name))
    .WithMetrics(m => m.AddMeter(MessagingTelemetry.Name));

The outbox stores the W3C trace context of the request that raised each event, and the relay publishes it in that trace, so a request, its published event and the consumer's handling show up as one trace. Metrics cover published, failed and dead-lettered messages, pending counts, publish lag, handled and duplicate inbox messages, and cleanup.

Upgrading from 4.1

Nothing to change. In 4.2:

  • Inbox rows are dead-lettered when Wolverine actually moves a message to its error queue, instead of by counting attempts, so custom retry policies and redeliveries after a crash no longer throw it off. InboxOptions.BrokerDeliveryAttempts stays as an opt-in fallback; AddGMMessaging no longer sets it. If you replaced GM's failure policy, add AndMarkGMInboxDeadLettered() to your rules.
  • UpgradeExchanges restores an exchange's bindings when RabbitMq:ManagementUri is set.
  • New: per-host IntegrationEventRegistry (isolated: true), payload protection, the GM.Messaging.AspNetCore admin endpoints, and BodyContains / DeadLetteredBefore broker filters.

Upgrading from 4.0

Nothing to change. Behaviour to know about in 4.1:

  • Inbox rows of ProcessAsync handlers that fail on the broker's last delivery are now dead-lettered (shown by IInboxAdministration and the backlog health check). RequeueAsync / RequeueAllDeadLetteredAsync skip them; replay them from the broker's dead-letter queue.
  • IBrokerQueueAdministration gained filtered overloads; the old ones remain. If you implement the interface yourself (a test fake), implement the three new members.
  • Registering a different upcaster for the same event and version, or configuring different JSON options twice, now throws.

Upgrading from 3.x

No database changes. 4.0 declares every exchange in ProducerTopology / ConsumerTopology with an alternate-exchange argument, and RabbitMQ refuses to redeclare an existing exchange with different arguments. A service that finds such an exchange stops at startup with a message naming it. Either delete those exchanges once (the services recreate them, and consumers rebind their queues, at startup), set Messaging:RabbitMq:UpgradeExchanges to true in one service to have it delete and recreate them (with Messaging:RabbitMq:ManagementUri set it restores their bindings at once; without it, restart the consumers, which rebind, and move anything that landed in gm.unrouted back), or keep the old behaviour by setting Messaging:RabbitMq:UnroutedExchange to "" in every producer and consumer. Producers and consumers of the same exchange must use the same setting.

Also new in 4.0, without breaking changes for callers:

  • Wolverine's default serializer is GM's (same JSON as storage, versions in a header). Payloads are still plain JSON.
  • Handlers can take the inbox's DbContext directly; remove any CodeGeneration.AlwaysUseServiceLocationFor<YourDbContext>() you added (it's harmless if left).
  • IBrokerQueueAdministration, AddGMIntegrationEvents, and cross-process wake-ups (AddGMOutboxWakeUp, OutboxRelay:WakeUpExchange).
  • OutboxSignal.Notify() now also tells other processes; use WakeUp() to wake only this process's relay.

Upgrading from 2.x

3.0 adds columns again, so add an EF Core migration in each service that maps the tables:

  • outbox_messages: event_version (default 1), ordering_key, and the ix_outbox_messages_ordering index.
  • inbox_messages: event_version (default 1).

Also changed:

  • IInboxProcessor has overloads without a consumer name (custom implementations must add them).
  • OutboxMessage.From and Populate take an optional orderingKey, and InboxMessage.Create an optional eventVersion (recompile; source-compatible).
  • Payloads are written with IntegrationEventSerializer.Options and read case-insensitively.

Upgrading from 1.x

2.0 adds columns to both tables, so add an EF Core migration in each service that maps them:

  • outbox_messages: next_attempt_at_utc, dead_lettered_at_utc, locked_by, locked_until_utc, trace_parent, and the ix_outbox_messages_pending index.
  • inbox_messages: attempts, ingested, next_attempt_at_utc, dead_lettered_at_utc, locked_by, locked_until_utc, trace_parent, and the ix_inbox_messages_pending index.

Also changed:

  • IInboxStore<T>, IOutboxDbContext<T> and AddGMInboxProcessor<T>() are gone; AddGMInbox and AddGMOutboxRelay work on the DbContext directly.
  • IInboxProcessor is scoped (it shares the handler's DbContext), so resolve it per message or scope, not from the root provider.
  • New rows store the event's full type name instead of its assembly-qualified name. Existing rows still resolve.
  • Published outbox messages (after 7 days) and handled inbox rows (after 30 days) are now deleted. Set RetentionDays to 0 to keep them.
  • Rows ingested by 1.x have ingested = false after the migration, so the inbox worker ignores them. Finish them with your existing poller, or set ingested = true on them.

Local infrastructure

A docker-compose.yml is included to run PostgreSQL + RabbitMQ locally:

docker compose up gm.messaging.postgres gm.messaging.rabbitmq

Requirements

  • .NET 10 SDK
  • RabbitMQ (and a relational database for the outbox/inbox).

Contributing & releases

Versioning is automated from Conventional Commits — see CONTRIBUTING.md. All four packages release together under one version.

License

MIT — see LICENSE.

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
5.0.0 64 11/17/2026
4.14.0 137 11/17/2026
4.13.0 57 11/17/2026
4.12.0 64 11/17/2026
4.11.0 63 11/17/2026
4.10.0 56 11/17/2026
4.9.0 56 11/17/2026
4.8.0 60 11/17/2026
4.7.0 57 11/17/2026
4.6.0 61 11/17/2026
4.5.0 71 11/16/2026
4.4.0 90 11/16/2026
4.3.0 71 11/16/2026
4.2.0 83 11/16/2026