İçeriğe geç
Docs Try Aspire
Docs Try

Connect to NATS

Bu içerik henüz dilinizde mevcut değil.

NATS logo

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

When you reference a NATS 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 NATS client integration for automatic dependency injection, health checks, and telemetry.

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

The NATS resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the NATS server
PortThe port number the NATS server is listening on
UsernameThe username for authentication
PasswordThe password for authentication
UriThe connection URI, with the format nats://{Username}:{Password}@{Host}:{Port}

Example connection string:

Uri: nats://admin:p%40ssw0rd1@localhost:4222

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

For C# apps, the recommended approach is the Aspire NATS client integration. It registers an INatsConnection 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.NATS.Net NuGet package in the client-consuming project:

.NET CLI — Add Aspire.NATS.Net package
dotnet add package Aspire.NATS.Net

In Program.cs, call AddNatsClient on your IHostApplicationBuilder to register an INatsConnection:

C# — Program.cs
builder.AddNatsClient(connectionName: "nats");

Resolve the connection through dependency injection:

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

To register multiple INatsConnection instances with different connection names, use AddKeyedNatsClient:

C# — Program.cs
builder.AddKeyedNatsClient(name: "products");
builder.AddKeyedNatsClient(name: "orders");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("products")] INatsConnection productsConnection,
[FromKeyedServices("orders")] INatsConnection ordersConnection)
{
// Use connections...
}

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

The Aspire NATS 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 AddNatsClient:

C# — Program.cs
builder.AddNatsClient("nats");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"nats": "nats://localhost:4222"
}
}

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

JSON — appsettings.json
{
"Aspire": {
"Nats": {
"Client": {
"ConnectionString": "nats://localhost:4222",
"DisableHealthChecks": false,
"DisableTracing": false
}
}
}
}

For the complete NATS client integration JSON schema, see Aspire.NATS.Net/ConfigurationSchema.json.

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

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

Aspire client integrations enable health checks by default. The NATS client integration adds a health check that verifies the NATS instance is reachable and can execute commands. The health check is wired into the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

The Aspire NATS client integration automatically configures tracing through OpenTelemetry.

Tracing activities:

  • NATS — emitted by NatsConnection
  • NATS.Net — emitted by the NATS .NET client library

For more information about tracing activities, see NATS .NET client library: OpenTelemetry support.

Any of these telemetry features can be disabled through the configuration options above.

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 📦 NATS.Net NuGet package:

C# — Program.cs
using NATS.Client.Core;
var connectionUri = Environment.GetEnvironmentVariable("NATS_URI");
await using var connection = new NatsConnection(
NatsOpts.Default with { Url = connectionUri! });
await connection.ConnectAsync();
// Use connection...