.NET Aspire Redis®* integration
Includes: Hosting integration and Client integration
Redis is the world's fastest data platform for caching, vector search, and NoSQL databases. The .NET Aspire Redis integration enables you to connect to existing Redis instances, or create new instances from .NET with the docker.io/library/redis
container image.
Garnet is a a high-performance cache-store from Microsoft Research and complies with the Redis serialization protocol (RESP). The .NET Aspire Redis integration enables you to connect to existing Garnet instances, or create new instances from .NET with the ghcr.io/microsoft/garnet
container image.
Valkey is a Redis fork and complies with the Redis serialization protocol (RESP). It's a high-performance key/value datastore that supports a variety of workloads such as caching, message queues, and can act as a primary database. The .NET Aspire Redis integration enables you to connect to existing Valkey instances, or create new instances from .NET with the docker.io/valkey/valkey
container image.
Hosting integration
The Redis hosting integration models a Redis resource as the RedisResource type. To access this type and APIs that allow you to add it to your 📦 Aspire.Hosting.Redis NuGet package in the app host project.
dotnet add package Aspire.Hosting.Redis
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Add Redis resource
In your app host project, call AddRedis on the builder
instance to add a Redis resource:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache");
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// 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/Redis/Redis
image, it creates a new Redis instance on your local machine. A reference to your Redis resource (the cache
variable) is added to the ExampleProject
.
The WithReference method configures a connection in the ExampleProject
named "cache"
. For more information, see Container resource lifecycle.
Tip
If you'd rather connect to an existing Redis instance, call AddConnectionString instead. For more information, see Reference existing resources.
Add Redis resource with Redis Insights
To add the Redis Insights to the Redis resource, call the WithRedisInsight
method:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache")
.WithRedisInsight();
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
Redis Insights is a free graphical interface for analyzing Redis data across all operating systems and Redis deployments with the help of our AI assistant, Redis Copilot. .NET Aspire adds another container image docker.io/redis/redisinsight
to the app host that runs the commander app.
Note
To configure the host port for the RedisInsightResource
chain a call to the WithHostPort
API and provide the desired port number.
Add Redis resource with Redis Commander
To add the Redis Commander to the Redis resource, call the WithRedisCommander method:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache")
.WithRedisCommander();
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
Redis Commander is a Node.js web application used to view, edit, and manage a Redis Database. .NET Aspire adds another container image docker.io/rediscommander/redis-commander
to the app host that runs the commander app.
Tip
To configure the host port for the RedisCommanderResource chain a call to the WithHostPort API and provide the desired port number.
Add Redis resource with data volume
To add a data volume to the Redis resource, call the WithDataVolume method on the Redis resource:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache")
.WithDataVolume(isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
The data volume is used to persist the Redis data outside the lifecycle of its container. The data volume is mounted at the /data
path in the Redis container and when a name
parameter isn't provided, the name is generated at random. For more information on data volumes and details on why they're preferred over bind mounts, see Docker docs: Volumes.
Add Redis resource with data bind mount
To add a data bind mount to the Redis resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache")
.WithDataBindMount(
source: @"C:\Redis\Data",
isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// 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 Redis data across container restarts. The data bind mount is mounted at the C:\Redis\Data
on Windows (or /Redis/Data
on Unix) path on the host machine in the Redis container. For more information on data bind mounts, see Docker docs: Bind mounts.
Add Redis resource with persistence
To add persistence to the Redis resource, call the WithPersistence method with either the data volume or data bind mount:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddRedis("cache")
.WithDataVolume()
.WithPersistence(
interval: TimeSpan.FromMinutes(5),
keysChangedThreshold: 100);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
The preceding code adds persistence to the Redis resource by taking snapshots of the Redis data at a specified interval and threshold. The interval
is time between snapshot exports and the keysChangedThreshold
is the number of key change operations required to trigger a snapshot. For more information on persistence, see Redis docs: Persistence.
The Garnet hosting integration models a Garnet resource as the GarnetResource type. To access this type and APIs that allow you to add it to your 📦 Aspire.Hosting.Garnet NuGet package in the app host project.
dotnet add package Aspire.Hosting.Garnet
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Add Garnet resource
In your app host project, call AddGarnet on the builder
instance to add a Garnet resource:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddGarnet("cache");
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// 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 ghcr.io/microsoft/garnet
image, it creates a new Garnet instance on your local machine. A reference to your Garnet resource (the cache
variable) is added to the ExampleProject
.
The WithReference method configures a connection in the ExampleProject
named "cache"
. For more information, see Container resource lifecycle.
Tip
If you'd rather connect to an existing Garnet instance, call AddConnectionString instead. For more information, see Reference existing resources.
Add Garnet resource with data volume
To add a data volume to the Garnet resource, call the AddGarnet method on the Garnet resource:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddGarnet("cache")
.WithDataVolume(isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
The data volume is used to persist the Garnet data outside the lifecycle of its container. The data volume is mounted at the /data
path in the Garnet container and when a name
parameter isn't provided, the name is generated at random. For more information on data volumes and details on why they're preferred over bind mounts, see Docker docs: Volumes.
Add Garnet resource with data bind mount
To add a data bind mount to the Garnet resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddGarnet("cache")
.WithDataBindMount(
source: @"C:\Garnet\Data",
isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// 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 Garnet data across container restarts. The data bind mount is mounted at the C:\Garnet\Data
on Windows (or /Garnet/Data
on Unix) path on the host machine in the Garnet container. For more information on data bind mounts, see Docker docs: Bind mounts.
Add Garnet resource with persistence
To add persistence to the Garnet resource, call the WithPersistence method with either the data volume or data bind mount:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddGarnet("cache")
.WithDataVolume()
.WithPersistence(
interval: TimeSpan.FromMinutes(5),
keysChangedThreshold: 100);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
The preceding code adds persistence to the Redis resource by taking snapshots of the Garnet data at a specified interval and threshold. The interval
is time between snapshot exports and the keysChangedThreshold
is the number of key change operations required to trigger a snapshot. For more information on persistence, see Redis docs: Persistence.
The Valkey hosting integration models a Valkey resource as the ValkeyResource type. To access this type and APIs that allow you to add it to your 📦 Aspire.Hosting.Valkey NuGet package in the app host project.
dotnet add package Aspire.Hosting.Valkey
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Add Valkey resource
In your app host project, call AddValkey on the builder
instance to add a Valkey resource:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddValkey("cache");
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// 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/valkey/valkey
image, it creates a new Valkey instance on your local machine. A reference to your Valkey resource (the cache
variable) is added to the ExampleProject
.
The WithReference method configures a connection in the ExampleProject
named "cache"
. For more information, see Container resource lifecycle.
Tip
If you'd rather connect to an existing Valkey instance, call AddConnectionString instead. For more information, see Reference existing resources.
Add Valkey resource with data volume
To add a data volume to the Valkey resource, call the AddValkey method on the Valkey resource:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddValkey("cache")
.WithDataVolume(isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
The data volume is used to persist the Valkey data outside the lifecycle of its container. The data volume is mounted at the /data
path in the Valkey container and when a name
parameter isn't provided, the name is generated at random. For more information on data volumes and details on why they're preferred over bind mounts, see Docker docs: Volumes.
Add Valkey resource with data bind mount
To add a data bind mount to the Valkey resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddValkey("cache")
.WithDataBindMount(
source: @"C:\Valkey\Data",
isReadOnly: false);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// 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 Valkey data across container restarts. The data bind mount is mounted at the C:\Valkey\Data
on Windows (or /Valkey/Data
on Unix) path on the host machine in the Valkey container. For more information on data bind mounts, see Docker docs: Bind mounts.
Add Valkey resource with persistence
To add persistence to the Valkey resource, call the WithPersistence method with either the data volume or data bind mount:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddValkey("cache")
.WithDataVolume()
.WithPersistence(
interval: TimeSpan.FromMinutes(5),
keysChangedThreshold: 100);
builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
// After adding all resources, run the app...
The preceding code adds persistence to the Redis resource by taking snapshots of the Valkey data at a specified interval and threshold. The interval
is time between snapshot exports and the keysChangedThreshold
is the number of key change operations required to trigger a snapshot. For more information on persistence, see Redis docs: Persistence.
Hosting integration health checks
The Redis hosting integration automatically adds a health check for the appropriate resource type. The health check verifies that the server is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.Redis NuGet package.
Client integration
To get started with the .NET Aspire Stack Exchange Redis client integration, install the 📦 Aspire.StackExchange.Redis NuGet package in the client-consuming project, that is, the project for the application that uses the Redis client. The Redis client integration registers an an IConnectionMultiplexer instance that you can use to interact with Redis.
dotnet add package Aspire.StackExchange.Redis
Add Redis client
In the Program.cs file of your client-consuming project, call the AddRedisClient extension method on any IHostApplicationBuilder to register an IConnectionMultiplexer
for use via the dependency injection container. The method takes a connection name parameter.
builder.AddRedisClient(connectionName: "cache");
Tip
The connectionName
parameter must match the name used when adding the Redis resource in the app host project. For more information, see Add Redis resource.
Tip
The connectionName
parameter must match the name used when adding the Garnet resource in the app host project. For more information, see Add Garnet resource.
Tip
The connectionName
parameter must match the name used when adding the Valkey resource in the app host project. For more information, see Add Valkey resource.
You can then retrieve the IConnection
instance using dependency injection. For example, to retrieve the connection from an example service:
public class ExampleService(IConnectionMultiplexer connectionMux)
{
// Use connection multiplexer...
}
For more information on dependency injection, see .NET dependency injection.
Add keyed Redis client
There might be situations where you want to register multiple IConnectionMultiplexer
instances with different connection names. To register keyed Redis clients, call the AddKeyedRedisClient method:
builder.AddKeyedRedisClient(name: "chat");
builder.AddKeyedRedisClient(name: "queue");
Then you can retrieve the IConnectionMultiplexer
instances using dependency injection. For example, to retrieve the connection from an example service:
public class ExampleService(
[FromKeyedServices("chat")] IConnectionMultiplexer chatConnectionMux,
[FromKeyedServices("queue")] IConnectionMultiplexer queueConnectionMux)
{
// Use connections...
}
For more information on keyed services, see .NET dependency injection: Keyed services.
Configuration
The .NET Aspire Stack Exchange Redis client integration provides multiple options to configure the Redis connection based on the requirements and conventions of your project.
Use a connection string
When using a connection string from the ConnectionStrings
configuration section, you can provide the name of the connection string when calling AddRedis:
builder.AddRedis("cache");
When using a connection string from the ConnectionStrings
configuration section, you can provide the name of the connection string when calling AddGarnet:
builder.AddGarnet("cache");
When using a connection string from the ConnectionStrings
configuration section, you can provide the name of the connection string when calling AddValkey:
builder.AddValkey("cache");
Then the connection string will be retrieved from the ConnectionStrings
configuration section:
{
"ConnectionStrings": {
"cache": "localhost:6379"
}
}
For more information on how to format this connection string, see the Stack Exchange Redis configuration docs.
Use configuration providers
The .NET Aspire Stack Exchange Redis integration supports Microsoft.Extensions.Configuration. It loads the StackExchangeRedisSettings from configuration by using the Aspire:StackExchange:Redis
key. Example appsettings.json that configures some of the options:
{
"Aspire": {
"StackExchange": {
"Redis": {
"ConnectionString": "localhost:6379",
"DisableHealthChecks": true,
"DisableTracing": false
}
}
}
}
For the complete Redis client integration JSON schema, see Aspire.StackExchange.Redis/ConfigurationSchema.json.
Use inline delegates
You can also pass the Action<StackExchangeRedisSettings>
delegate to set up some or all the options inline, for example to configure DisableTracing
:
builder.AddRedisClient(
"cache",
static settings => settings.DisableTracing = true);
Client integration health checks
By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.
The .NET Aspire Stack Exchange Redis integration handles the following:
- Adds the health check when StackExchangeRedisSettings.DisableHealthChecks is
false
, which attempts to connect to the container instance. - Integrates with the
/health
HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.
Observability and telemetry
.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 might 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.
Logging
The .NET Aspire Stack Exchange Redis integration uses the following log categories:
Aspire.StackExchange.Redis
Tracing
The .NET Aspire Stack Exchange Redis integration will emit the following tracing activities using OpenTelemetry:
OpenTelemetry.Instrumentation.StackExchangeRedis
Metrics
The .NET Aspire Stack Exchange Redis integration currently doesn't support metrics by default due to limitations with the StackExchange.Redis
library.
Azure Redis hosting integration
To deploy your Redis resources to Azure, install the 📦 Aspire.Hosting.Azure.Redis NuGet package:
dotnet add package Aspire.Hosting.Azure.Redis
Add Azure Cache for Redis server resource
After you've installed the .NET Aspire hosting Azure Redis package, call the AddAzureRedis
extension method in your app host project:
var builder = DistributedApplication.CreateBuilder(args);
var cache = builder.AddAzureRedis("azcache")
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(cache);
The preceding call to AddAzureRedis
configures the Redis server resource to be deployed as an Azure Cache for Redis.
Important
By default, AddAzureRedis
configures Microsoft Entra ID authentication. This requires changes to applications that need to connect to these resources, for example, client integrations.
Add Azure Cache for Redis client
By default, when you call AddAzureRedis
in your Redis hosting integration, it configures 📦 Microsoft.Azure.StackExchangeRedis NuGet package to enable authentication:
dotnet add package Microsoft.Azure.StackExchangeRedis
The Redis connection can be consumed using the client integration and Microsoft.Azure.StackExchangeRedis
. Consider the following configuration code:
var azureOptionsProvider = new AzureOptionsProvider();
var configurationOptions = ConfigurationOptions.Parse(
builder.Configuration.GetConnectionString("cache") ??
throw new InvalidOperationException("Could not find a 'cache' connection string."));
if (configurationOptions.EndPoints.Any(azureOptionsProvider.IsMatch))
{
await configurationOptions.ConfigureForAzureWithTokenCredentialAsync(
new DefaultAzureCredential());
}
builder.AddRedisClient("cache", configureOptions: options =>
{
options.Defaults = configurationOptions.Defaults;
});
For more information, see the Microsoft.Azure.StackExchangeRedis repo.
See also
*: Redis is a registered trademark of Redis Ltd. Any rights therein are reserved to Redis Ltd. Any use by Microsoft is for referential purposes only and does not indicate any sponsorship, endorsement or affiliation between Redis and Microsoft. Return to top?