Chatter.MessageBrokers.RabbitMQ
0.5.0
See the version list below for details.
dotnet add package Chatter.MessageBrokers.RabbitMQ --version 0.5.0
NuGet\Install-Package Chatter.MessageBrokers.RabbitMQ -Version 0.5.0
<PackageReference Include="Chatter.MessageBrokers.RabbitMQ" Version="0.5.0" />
<PackageVersion Include="Chatter.MessageBrokers.RabbitMQ" Version="0.5.0" />
<PackageReference Include="Chatter.MessageBrokers.RabbitMQ" />
paket add Chatter.MessageBrokers.RabbitMQ --version 0.5.0
#r "nuget: Chatter.MessageBrokers.RabbitMQ, 0.5.0"
#:package Chatter.MessageBrokers.RabbitMQ@0.5.0
#addin nuget:?package=Chatter.MessageBrokers.RabbitMQ&version=0.5.0
#tool nuget:?package=Chatter.MessageBrokers.RabbitMQ&version=0.5.0
<a name="chatter-messagebrokers-rabbitmq"></a> Chatter.MessageBrokers.RabbitMQ
A RabbitMQ transport for Chatter.MessageBrokers — send and receive brokered messages over RabbitMQ exchanges and queues.
Overview
Chatter.MessageBrokers.RabbitMQ is a concrete, RabbitMQ implementation of the technology-agnostic interfaces defined by Chatter.MessageBrokers (itself built on Chatter.CQRS).
Where the core library defines IMessagingInfrastructureReceiver, IMessagingInfrastructureDispatcher, and the recovery abstractions (retry, circuit breaker), this package supplies the RabbitMQ realizations:
RabbitMqReceiverbridges RabbitMQ's push-consumer model to the core's blocking-pull loop via an internalChannel<T>buffer, so the core is never busy-polling.RabbitMqSenderpublishes messages through the default exchange (routing key = queue name) or an explicit exchange/routing-key override, with publisher confirms enabled so a publish is only treated as sent once the broker confirms it.RabbitMqRetryExceptionPredicatesProviderandRabbitMqCircuitBreakerExceptionPredicatesProviderclassify transient RabbitMQ faults so the shared retry/circuit-breaker recovery pipeline handles them correctly.
It registers itself with Chatter through an IChatterBuilder extension, AddRabbitMq(...), chained off AddMessageBrokers(...) — the same way the sibling Chatter.MessageBrokers.AzureServiceBus and Chatter.MessageBrokers.SqlServiceBroker packages register their adapters.
Installation
dotnet add package Chatter.MessageBrokers.RabbitMQ
Getting Started
Register Chatter CQRS, add message brokers, then add the RabbitMQ infrastructure with a connection and at least one queue receiver. The DI entry point is AddRabbitMq (in the Microsoft.Extensions.DependencyInjection namespace), configured via the RabbitMqOptionsBuilder.
using Microsoft.Extensions.DependencyInjection;
services.AddChatterCqrs(Configuration, builder =>
{
builder
.AddMessageBrokers()
.AddRabbitMq(rmq =>
{
rmq.AddRabbitMqOptions(hostName: "localhost",
userName: "guest",
password: "guest")
// register a receiver for a message type bound to a RabbitMQ queue, with a
// poison target — the receiver fails fast at startup without a dead-letter
// or error queue path configured
.AddQueueReceiver<MyIntegrationEvent>(
queueName: "my-integration-event",
deadLetterQueuePath: "my-integration-event-deadletter");
});
});
The dead-letter (or error) queue is provisioned externally — see Required topology.
Alternatively, connect via AMQP URI:
rmq.AddRabbitMqOptions(uri: "amqp://guest:guest@localhost:5672/");
AddQueueReceiver<TMessage> binds a Chatter.CQRS.IMessage type to a RabbitMQ queue. Optional parameters let you set an error/dead-letter queue path, description, transaction mode, and maxReceiveAttempts (default 10):
rmq.AddQueueReceiver<MyIntegrationEvent>(
queueName: "my-integration-event",
errorQueuePath: "my-integration-event-error",
transactionMode: TransactionMode.ReceiveOnly,
deadLetterQueuePath: "my-integration-event-deadletter",
maxReceiveAttempts: 5);
Sending / publishing
Within a message handler, dispatch out through the broker using the standard Chatter context, selecting the RabbitMQ infrastructure with the .RabbitMq() context selector:
using Chatter.CQRS.Context;
public class MyHandler : IMessageHandler<SomeCommand>
{
public Task Handle(SomeCommand message, IMessageHandlerContext context)
{
return context.RabbitMq()
.Send(new AnotherCommand(), "another-command");
}
}
context.RabbitMq() stamps the outbound message to route through the RabbitMQ infrastructure and returns an IMessageBrokerContext, which exposes Send, Publish, and Forward. The destination is the target queue name under the default-exchange convention (see Addressing).
Configuration
Options are modeled by RabbitMqOptions and assembled with RabbitMqOptionsBuilder. Configure them by calling AddRabbitMqOptions(...) or using the fluent With... methods.
Connection
| Builder method | Purpose |
|---|---|
AddRabbitMqOptions(uri: "amqp://...") |
Connect via AMQP URI (takes precedence over discrete host/credential settings when both are set). |
AddRabbitMqOptions(hostName: "...", userName: "...", password: "...") |
Connect via discrete host and credentials. |
WithUri(string uri) |
Set the AMQP URI after initial configuration. |
WithHostName(string hostName) |
Set the broker host name after initial configuration. |
WithCredentials(string userName, string password) |
Set authentication credentials after initial configuration. |
WithTls(string serverName = null) |
Connect the discrete host/credential path over TLS (default off). Sets RabbitMqOptions.UseTls and, optionally, TlsServerName (defaults to HostName). Ignored when a connection URI is configured. |
Build() throws if neither a URI nor a host name is supplied, or if no AddRabbitMqOptions(...) call was made. Build() also throws if WithTls(...) is used alongside a configured connection URI that is not an amqps:// URI — the URI takes precedence over the discrete settings, so that combination would otherwise connect in the clear.
TLS
Two independent paths enable TLS, and only one takes effect at a time:
- Connection URI: an
amqps://URI enables TLS for that connection, handled entirely by the RabbitMQ client. - Discrete settings:
WithTls(serverName)enables TLS for the discrete host/credential path, defaulting the validated server name toHostNameand defaulting the port to5671. It has no effect when a connection URI is configured — the URI scheme determines the transport — andBuild()rejects aWithTls(...)call made alongside a plaintext URI rather than silently dropping it.
There is no option to disable or relax certificate validation on either path. The discrete path is deliberately stricter than the client's own amqps URI handling, which relaxes AcceptablePolicyErrors to tolerate a certificate name mismatch — the discrete path leaves every SslOption member other than Enabled and ServerName at its strict default, so a server name that does not match the broker's certificate fails the handshake.
Receiver options
| Property | Builder method | Default | Purpose |
|---|---|---|---|
Prefetch |
WithPrefetch(int) |
1 |
Maximum number of unacknowledged messages the broker delivers to a receiver before waiting for acknowledgements. Size this >= MaxConcurrentCalls to keep all processing workers saturated. |
QueueType |
WithQueueType(QueueType) |
QueueType.Quorum |
Delivery-count strategy: Quorum reads the native x-delivery-count header; Classic uses a header-stamped republish counter. Quorum is the documented recommendation — see Delivery counting. |
MessageBodyType |
WithMessageBodyType(string) / WithJsonBodyType() |
application/json; charset=utf-8 |
Content type used to encode/decode the message body. |
Addressing
The RabbitMQ adapter uses a default-exchange convention: a bare Destination names a queue, and the sender publishes to RabbitMQ's default exchange ("") with a routing key equal to that queue name. Routing key and queue name coincide only under this convention.
To route through a non-default exchange with an explicit routing key on the handler path, pass a SendOptions (or PublishOptions) with .WithRabbitMqRouting(exchange, routingKey):
using Chatter.CQRS.Context;
using Chatter.MessageBrokers.Routing.Options;
public class MyHandler : IMessageHandler<SomeCommand>
{
public Task Handle(SomeCommand message, IMessageHandlerContext context)
=> context.RabbitMq().Send(
new AnotherCommand(),
"my-destination",
new SendOptions().WithRabbitMqRouting("my.exchange", "my.routing.key"));
}
WithRabbitMqRouting stamps the exchange and routing key into the options' message context; the core dispatcher merges that context into the outbound message before handing it to the sender, which then publishes to the specified exchange with the specified routing key instead of the default-exchange convention.
For the explicit-outbound / outbox path (where you construct an OutboundBrokeredMessage directly), the OutboundBrokeredMessage.WithRabbitMqRouting(exchange, routingKey) extension remains available and stamps the context directly on the outbound instance.
Delivery counting
Chatter's Max Receives Exceeded concept requires counting how many times a message has been delivered so a poison message can be routed to the dead-letter/error queue once the configured limit is reached. The adapter selects a counting strategy based on QueueType:
Quorum queues (default, recommended)
On quorum queues, RabbitMQ maintains a native per-message x-delivery-count header that is incremented on every redelivery. The adapter reads this header directly. On failure, the message is negatively acknowledged with requeue: true and the broker redelivers it with an incremented count. There is no duplicate risk and no ordering change — quorum queues are the recommended choice.
Classic queues
Classic queues do not expose a native delivery counter. The adapter implements a header-stamped republish counter: on retry it republishes the message to its own queue with an incremented x-chatter-delivery-count header (publisher-confirmed before the original is acknowledged), then acknowledges the original delivery.
This approach carries documented trade-offs (per ADR 0001):
- Rare duplicate: a crash between the confirmed republish and the acknowledgement of the original yields a duplicate delivery (never a loss). This is mitigated by publisher confirms and absorbed downstream by the Chatter Inbox (idempotent, once-only handling).
- Loss of head-of-queue ordering: the republished message lands at the tail of the queue.
Use QueueType.Classic only when quorum queues are not available and you accept these trade-offs.
rmq.AddRabbitMqOptions(hostName: "localhost")
.WithQueueType(QueueType.Classic);
Dead-letter / error routing
When Max Receives Exceeded trips, the adapter republishes the message body directly to the attribute-declared DeadletterQueueName or ErrorQueueName path (an adapter-owned republish), then acknowledges the original delivery. This is authoritative over any broker-side dead-letter exchange (DLX) configured on the work queue — the declared name is the destination, regardless of broker DLX configuration.
Configure the dead-letter and error queue paths in AddQueueReceiver<TMessage>(...):
rmq.AddQueueReceiver<MyIntegrationEvent>(
queueName: "my-integration-event",
errorQueuePath: "my-integration-event-error",
deadLetterQueuePath: "my-integration-event-deadletter");
Both queues must be provisioned externally before the application starts (see Required topology). A configured dead-letter or error queue path is verified at receiver startup: the adapter passively declares the queue (an existence check, not a provisioning call — see Required topology) and fails fast, naming the missing queue, if it does not exist. Previously a missing poison destination surfaced only as a silent stall on the first poison message, once the deadletter republish faulted and left the original delivery unsettled.
Transactions
The adapter supports the broker-agnostic transaction modes that map cleanly onto AMQP:
| Mode | Support |
|---|---|
TransactionMode.None |
Supported, at-most-once. The consumer registers with autoAck (the AMQP ReceiveAndDelete equivalent, matching the Azure Service Bus adapter), so the broker removes the delivery at receive — a handler failure or a process crash drops the message rather than redelivering it. |
TransactionMode.ReceiveOnly |
Supported. Ack/nack scope the receive only. |
TransactionMode.FullAtomicityViaInfrastructure |
Rejected at startup. RabbitMQ offers no atomic receive-and-send across the consume and a downstream publish. Use the Outbox for transactional send. |
FullAtomicityViaInfrastructure is rejected at registration time — the application will not start — with a message directing you to TransactionMode.None or TransactionMode.ReceiveOnly and the Outbox.
Known limitations
Single RabbitMQ queue receiver per process
This package supports exactly one RabbitMQ queue receiver per process. Registering more than one RabbitMQ queue receiver fails fast at startup with NotSupportedException — the connection source owns one receive channel and one consumer registration, so a second receiver would clobber the first and recovery would re-register only the last. There is no silent stall: the error surfaces immediately at AddRabbitMq(...) registration time, before the host starts.
Full multi-receiver support is tracked in #195.
Required topology
This package is a transport over existing RabbitMQ topology — it provisions nothing. All exchanges, queues, bindings, and dead-letter routing must be created and owned externally before the application starts. The adapter assumes they exist.
This mirrors the Chatter.MessageBrokers.SqlServiceBroker manual-provisioning stance.
The dead-letter and error queues configured on a receiver are the one exception to "assumes they exist" without a runtime check: at startup the adapter verifies their existence with a passive declare (asking the broker whether the queue exists, which provisions nothing) and fails fast, naming the missing queue, rather than starting and silently stalling on the first poison message. This is verification, not provisioning — the adapter still never declares a queue, exchange, or binding.
Broker permissions for the poison-destination check
The passive declare creates nothing, but it is still an authorised operation. On RabbitMQ 4.3.1 and later a passive declare requires the connecting user to hold at least one of configure, write, or read on the target queue — any one is sufficient. (A non-passive declare specifically requires configure; this adapter never issues one.) Older brokers require no permission for a passive declare.
Grant the receiver's user any one of those three permissions on each configured dead-letter and error queue name. This is a new requirement as of 0.5.0: before the existence check the adapter issued no queue.declare at all, so a least-privilege user whose permission patterns matched none of the poison-destination names could still deadletter — a poison republish goes through the default exchange and is authorised against the exchange, not the destination queue. Such a user now fails at startup with ACCESS_REFUSED. That failure propagates unwrapped, so it is clearly distinguishable from the missing-queue failure, which is reported as an InvalidOperationException naming the queue and the option that configured it.
TransactionMode.None receivers probe nothing — they drop poison messages rather than republishing them — so they need no permission on any poison destination.
What you must provision
For each registered queue receiver, provision at minimum:
- A work queue matching the
queueNamepassed toAddQueueReceiver<TMessage>(...).- Quorum queues are the documented recommendation (
x-queue-type: quorumargument at declaration). - Classic queues are supported but carry the ADR 0001 delivery-counting trade-offs.
- Quorum queues are the documented recommendation (
- A dead-letter queue matching the
deadLetterQueuePath/errorQueuePathconfigured on the receiver (the adapter republishes to these by name — broker-side DLX configuration on the work queue is ignored by the adapter). - Bindings connecting any non-default exchange to the work queue when
.WithRabbitMqRouting(exchange, routingKey)is used.
Development topology
For local development, declare topology in a Dockerfile or docker-compose.yml using the RabbitMQ management definitions import or the rabbitmq_management plugin. A minimal docker-compose.yml fragment:
services:
rabbitmq:
image: rabbitmq:4-management
ports:
- "5672:5672"
- "15672:15672"
volumes:
- ./rabbitmq-definitions.json:/etc/rabbitmq/definitions.json
environment:
RABBITMQ_DEFAULT_USER: guest
RABBITMQ_DEFAULT_PASS: guest
Declare your queues and bindings in rabbitmq-definitions.json and the management plugin will import them on startup.
Production topology
Provision exchanges, queues, and bindings via your IaC tooling (Terraform, Pulumi, Ansible, etc.) before deploying the application.
Infrastructure type selection
To target a specific outbound message at the RabbitMQ infrastructure when multiple brokers are registered, use either the context.RabbitMq() selector in a handler or the InfrastructureTypes.RabbitMq() extension when configuring a receiver:
// In a handler — stamps the outbound message for RabbitMQ dispatch
context.RabbitMq().Send(new MyEvent(), "my-event-queue");
// In DI configuration — when constructing infrastructure explicitly
var infraType = new InfrastructureTypes().RabbitMq();
Domain Language
See the domain glossary for definitions of RabbitMq Receiver, RabbitMq Sender, Exchange, Queue, Routing Key, Binding, Dead-Letter Exchange / Dead-letter Queue, Delivery Count Strategy, RabbitMq Options, and Topology Ownership.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 was computed. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. 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. |
-
net10.0
- Chatter.MessageBrokers (>= 0.31.0)
- RabbitMQ.Client (>= 7.2.1)
-
net8.0
- Chatter.MessageBrokers (>= 0.31.0)
- RabbitMQ.Client (>= 7.2.1)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.