Events
Mar 17, 9 p.m. - Mar 21, 10 a.m.
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowThis browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Includes:
Hosting integration and
Client integration
NATS is a high-performance, secure, distributed messaging system. The .NET Aspire NATS integration enables you to connect to existing NATS instances, or create new instances from .NET with the docker.io/library/nats
container image.
NATS hosting integration for .NET Aspire models a NATS server as the NatsServerResource type. To access this type, install the 📦 Aspire.Hosting.Nats NuGet package in the app host project, then add it with the builder.
dotnet add package Aspire.Hosting.Nats
For more information, see dotnet add package or Manage package dependencies in .NET applications.
In your app host project, call AddNats on the builder
instance to add a NATS server resource:
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats");
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);
// After adding all resources, run the app...
When .NET Aspire adds a container image to the app host, as shown in the preceding example with the docker.io/library/nats
image, it creates a new NATS server instance on your local machine. A reference to your NATS server (the nats
variable) is added to the ExampleProject
.
The WithReference method configures a connection in the ExampleProject
named "nats"
. For more information, see Container resource lifecycle.
Tip
If you'd rather connect to an existing NATS server, call AddConnectionString instead. For more information, see Reference existing resources.
To add the NATS JetStream to the NATS server resource, call the WithJetStream method:
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats");
.WithJetStream();
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);
// After adding all resources, run the app...
The NATS JetStream functionality provides a built-in persistence engine called JetStream which enables messages to be stored and replayed at a later time.
When you want to explicitly provide the username and password, you can provide those as parameters. Consider the following alternative example:
var builder = DistributedApplication.CreateBuilder(args);
var username = builder.AddParameter("username");
var password = builder.AddParameter("password", secret: true);
var nats = builder.AddNats(
name: "nats",
userName: username,
password: password);
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);
// After adding all resources, run the app...
For more information, see External parameters.
To add a data volume to the NATS server resource, call the WithDataVolume method on the NATS server resource:
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats");
.WithDataVolume(isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);
// After adding all resources, run the app...
The data volume is used to persist the NATS server data outside the lifecycle of its container. The data volume is mounted at the /var/lib/nats
path in the NATS server container. A name is generated at random unless you provide a set the name
parameter. For more information on data volumes and details on why they're preferred over bind mounts, see Docker docs: Volumes.
To add a data bind mount to the NATS server resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var nats = builder.AddNats("nats");
.WithDataBindMount(
source: @"C:\NATS\Data",
isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(nats);
// After adding all resources, run the app...
Important
Data bind mounts have limited functionality compared to volumes, which offer better performance, portability, and security, making them more suitable for production environments. However, bind mounts allow direct access and modification of files on the host system, ideal for development and testing where real-time changes are needed.
Data bind mounts rely on the host machine's filesystem to persist the NATS server data across container restarts. The data bind mount is mounted at the C:\NATS\Data
on Windows (or /NATS/Data
on Unix) path on the host machine in the NATS server container. For more information on data bind mounts, see Docker docs: Bind mounts.
The NATS hosting integration automatically adds a health check for the NATS server resource. The health check verifies that the NATS server is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.Nats NuGet package.
To get started with the .NET Aspire NATS client integration, install the 📦 Aspire.NATS.Net NuGet package in the client-consuming project, that is, the project for the application that uses the NATS client. The NATS client integration registers an INatsConnection instance that you can use to interact with NATS.
dotnet add package Aspire.NATS.Net
In the Program.cs file of your client-consuming project, call the AddNatsClient extension method on any IHostApplicationBuilder to register an INatsConnection
for use via the dependency injection container. The method takes a connection name parameter.
builder.AddNatsClient(connectionName: "nats");
Tip
The connectionName
parameter must match the name used when adding the NATS server resource in the app host project. For more information, see Add NATS server resource.
You can then retrieve the INatsConnection
instance using dependency injection. For example, to retrieve the client from a service:
public class ExampleService(INatsConnection connection)
{
// Use connection...
}
For more information on dependency injection, see .NET dependency injection.
There might be situations where you want to register multiple INatsConnection
instances with different connection names. To register keyed NATS clients, call the AddKeyedNatsClient method:
builder.AddKeyedNatsClient(name: "chat");
builder.AddKeyedNatsClient(name: "queue");
Then you can retrieve the IConnection
instances using dependency injection. For example, to retrieve the connection from an example service:
public class ExampleService(
[FromKeyedServices("chat")] INatsConnection chatConnection,
[FromKeyedServices("queue")] INatsConnection queueConnection)
{
// Use connections...
}
For more information on keyed services, see .NET dependency injection: Keyed services.
The .NET Aspire NATS integration provides multiple options to configure the NATS connection based on the requirements and conventions of your project.
Provide the name of the connection string when you call builder.AddNatsClient
:
builder.AddNatsClient(connectionName: "nats");
The connection string is retrieved from the ConnectionStrings
configuration section:
{
"ConnectionStrings": {
"nats": "nats://nats:4222"
}
}
See the ConnectionString documentation for more information on how to format this connection string.
The .NET Aspire NATS integration supports Microsoft.Extensions.Configuration. It loads the NatsClientSettings from configuration by using the Aspire:Nats:Client
key. The following snippet is an example of a appsettings.json file that configures some of the options:
{
"Aspire": {
"Nats": {
"Client": {
"ConnectionString": "nats://nats:4222",
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}
}
For the complete NATS client integration JSON schema, see Aspire.NATS.Net/ConfigurationSchema.json.
Pass the Action<NatsClientSettings> configureSettings
delegate to set up some or all the options inline, for example to disable health checks from code:
builder.AddNatsClient(
"nats",
static settings => settings.DisableHealthChecks = true);
NATS isn't part of the .NET Aspire deployment manifest. It's recommended you set up a secure production NATS server outside of .NET Aspire.
By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.
The .NET Aspire NATS integration handles the following:
/health
HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic..NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.
The .NET Aspire NATS integration uses the following log categories:
NATS
The .NET Aspire NATS integration emits the following tracing activities:
NATS.Net
.NET Aspire feedback
.NET Aspire is an open source project. Select a link to provide feedback:
Events
Mar 17, 9 p.m. - Mar 21, 10 a.m.
Join the meetup series to build scalable AI solutions based on real-world use cases with fellow developers and experts.
Register nowTraining
Module
Use telemetry in a .NET Aspire project - Training
In this module, you'll learn about using telemetry to record the behavior of a cloud-native application and how the .NET Aspire stack makes it easier store data and view it later.