Salta ai contenuti
Docs Try Aspire
Docs Try

Connect to RabbitMQ

Questi contenuti non sono ancora disponibili nella tua lingua.

RabbitMQ logo

This page describes how consuming apps connect to a RabbitMQ resource that’s already modeled in your AppHost. For the AppHost API surface — adding a RabbitMQ server, data volumes, management plugin, parameters, and more — see RabbitMQ Hosting integration.

When you reference a RabbitMQ resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire RabbitMQ client integration for automatic dependency injection, health checks, and telemetry.

These connection properties are available when the AppHost models a typed RabbitMQ resource (for example, AddRabbitMQ("messaging")) and references it from a consuming app. If the AppHost uses AddConnectionString("messaging") or addConnectionString("messaging"), consuming apps receive a single ConnectionStrings value (ConnectionStrings:messaging / ConnectionStrings__messaging) instead of deconstructed resource variables such as MESSAGING_URI, MESSAGING_HOST, and MESSAGING_PORT.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called messaging becomes MESSAGING_URI.

The RabbitMQ server resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the RabbitMQ server
PortThe port number the RabbitMQ server is listening on
UsernameThe username for authentication
PasswordThe password for authentication
VirtualHostThe virtual host path. Defaults to / (the default virtual host). Embedded as the path component of the connection URI when non-default.
UriThe connection URI, with the format amqp://{Username}:{Password}@{Host}:{Port}

Example connection string:

Uri: amqp://guest:p%40ssw0rd1@localhost:5672

Environment variables and connection string formats

Section titled “Environment variables and connection string formats”

The way Aspire exposes connection information depends on how the RabbitMQ resource is modeled in your AppHost:

Using WithReference (typed RabbitMQ resource)

Section titled “Using WithReference (typed RabbitMQ resource)”

When your AppHost adds a typed RabbitMQ resource with builder.AddRabbitMQ("messaging") and references it with .WithReference(messaging), Aspire injects individual connection properties as environment variables using the [RESOURCE]_[PROPERTY] format:

  • MESSAGING_HOST = hostname
  • MESSAGING_PORT = port number
  • MESSAGING_USERNAME = username
  • MESSAGING_PASSWORD = password
  • MESSAGING_VIRTUALHOST = virtual host path (if set)
  • MESSAGING_URI = full connection URI

This is the recommended approach because Aspire manages the resource lifecycle, configuration, and provides typed client integrations.

Using AddConnectionString (external connection string)

Section titled “Using AddConnectionString (external connection string)”

When your AppHost uses builder.AddConnectionString("messaging") to reference an existing, pre-configured RabbitMQ server outside Aspire’s control, only a single connection string environment variable is injected:

  • ConnectionStrings__messaging = the full connection string provided to AddConnectionString

With this approach, there are no individual property variables (MESSAGING_HOST, MESSAGING_PORT, etc.). Consuming apps must parse the connection string themselves or use client libraries that accept a connection string directly.

Pick the language your consuming app is written in. Each example assumes your AppHost adds a RabbitMQ resource named messaging and references it from the consuming app.

For C# apps, the recommended approach is the Aspire RabbitMQ client integration. It registers an IConnection through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.

Install the 📦 Aspire.RabbitMQ.Client NuGet package in the client-consuming project:

.NET CLI — Add Aspire.RabbitMQ.Client package
dotnet add package Aspire.RabbitMQ.Client

In Program.cs, call AddRabbitMQClient on your IHostApplicationBuilder to register an IConnection:

C# — Program.cs
builder.AddRabbitMQClient(connectionName: "messaging");

Resolve the connection through dependency injection:

C# — ExampleService.cs
public class ExampleService(IConnection connection)
{
// Use connection...
}

To register multiple IConnection instances with different connection names, use AddKeyedRabbitMQClient:

C# — Program.cs
builder.AddKeyedRabbitMQClient(name: "chat");
builder.AddKeyedRabbitMQClient(name: "queue");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("chat")] IConnection chatConnection,
[FromKeyedServices("queue")] IConnection queueConnection)
{
// Use connections...
}

For more information, see .NET dependency injection: Keyed services.

The Aspire RabbitMQ client integration offers multiple ways to provide configuration.

Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddRabbitMQClient:

C# — Program.cs
builder.AddRabbitMQClient("messaging");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"messaging": "amqp://username:password@localhost:5672"
}
}

For more information on how to format this connection string, see the RabbitMQ URI specification.

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads RabbitMQClientSettings from appsettings.json (or any other configuration source) by using the Aspire:RabbitMQ:Client key:

JSON — appsettings.json
{
"Aspire": {
"RabbitMQ": {
"Client": {
"ConnectionString": "amqp://username:password@localhost:5672",
"DisableHealthChecks": false,
"DisableTracing": false,
"MaxConnectRetryCount": 2
}
}
}
}

For the complete JSON schema, see Aspire.RabbitMQ.Client/ConfigurationSchema.json.

Inline delegates. Pass an Action<RabbitMQClientSettings> to configure settings inline, for example to disable health checks:

C# — Program.cs
builder.AddRabbitMQClient(
"messaging",
static settings => settings.DisableHealthChecks = true);

You can also configure the IConnectionFactory inline using the configureConnectionFactory delegate parameter:

C# — Program.cs
builder.AddRabbitMQClient(
"messaging",
configureConnectionFactory:
static factory => factory.ClientProvidedName = "MyApp");

Auto activation opens the RabbitMQ connection during startup rather than lazily on first use, ensuring that any connectivity issues are detected early.

Auto activation is disabled by default in Aspire 9.5 to maintain backward compatibility. To enable it, set DisableAutoActivation to false:

C# — Program.cs
builder.AddRabbitMQClient("messaging", o => o.DisableAutoActivation = false);

Aspire client integrations enable health checks by default. The RabbitMQ client integration:

  • Adds a health check that attempts to connect to and create a channel on the RabbitMQ server when DisableHealthChecks is false.
  • Integrates with the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

The Aspire RabbitMQ client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

  • RabbitMQ.Client

Tracing activities:

  • Aspire.RabbitMQ.Client

Metrics: The RabbitMQ client integration doesn’t currently support metrics by default.

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and pass it directly to the 📦 RabbitMQ.Client library:

C# — Program.cs
using RabbitMQ.Client;
var uri = new Uri(Environment.GetEnvironmentVariable("MESSAGING_URI")!);
var factory = new ConnectionFactory { Uri = uri };
using var connection = await factory.CreateConnectionAsync();
using var channel = await connection.CreateChannelAsync();
// Use channel to publish or consume messages...