Connect to Redis distributed caching
Dieser Inhalt ist noch nicht in deiner Sprache verfügbar.
This page describes how consuming C# apps connect to a Redis resource that’s already modeled in the AppHost and register IDistributedCache using the Aspire.StackExchange.Redis.DistributedCaching client integration. For the AppHost API — adding the Redis resource, data volumes, persistence, and more — see Set up Redis distributed caching in the AppHost.
IDistributedCache is a C# / ASP.NET Core abstraction. TypeScript, Go, and Python consumers don’t have an equivalent; they should connect to Redis directly using the Redis client integration instead.
Connection properties
Section titled “Connection properties”When you reference a Redis resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables named [RESOURCE]_[PROPERTY]. For a resource called cache, the following properties are available:
| Property Name | Environment variable | Description |
|---|---|---|
Host | CACHE_HOST | The hostname or IP address of the Redis server |
Port | CACHE_PORT | The port number the Redis server is listening on |
Password | CACHE_PASSWORD | The password for authentication |
Uri | CACHE_URI | The full connection URI: redis://:{Password}@{Host}:{Port} |
Example connection string:
CACHE_URI=redis://:p%40ssw0rd1@localhost:6379The Aspire.StackExchange.Redis.DistributedCaching client integration reads these values automatically; you don’t need to read environment variables directly.
Connect from your app
Section titled “Connect from your app”IDistributedCache is a C# / ASP.NET Core abstraction — only the C# client integration is shown here. TypeScript, Go, and Python apps should connect to the same Redis resource directly with the Redis client integration instead.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.StackExchange.Redis.DistributedCaching NuGet package in the client-consuming project:
dotnet add package Aspire.StackExchange.Redis.DistributedCaching#:package Aspire.StackExchange.Redis.DistributedCaching@*<PackageReference Include="Aspire.StackExchange.Redis.DistributedCaching" Version="*" />Add Redis distributed cache
Section titled “Add Redis distributed cache”In Program.cs, call AddRedisDistributedCache on your IHostApplicationBuilder to register an IDistributedCache backed by Redis:
builder.AddRedisDistributedCache(connectionName: "cache");Resolve IDistributedCache through dependency injection:
public class ExampleService(IDistributedCache cache){ // Use cache...}Add keyed Redis distributed cache
Section titled “Add keyed Redis distributed cache”IDistributedCache is registered as a singleton, so only one instance can be registered in the normal DI container. If you need multiple Redis-backed IDistributedCache instances alongside an IConnectionMultiplexer, use AddKeyedRedisDistributedCache:
builder.AddKeyedRedisClient(name: "chat");builder.AddKeyedRedisDistributedCache(name: "product");Resolve the instances separately:
public class ExampleService( [FromKeyedServices("chat")] IConnectionMultiplexer chatConnectionMux, IDistributedCache productCache){ // chatConnectionMux — direct multiplexer for the "chat" Redis instance // productCache — IDistributedCache backed by the "product" Redis instance}Configuration
Section titled “Configuration”The client integration supports three configuration approaches that can be combined.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddRedisDistributedCache:
builder.AddRedisDistributedCache("cache");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "cache": "localhost:6379" }}For more information, see Stack Exchange Redis configuration.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads StackExchangeRedisSettings from appsettings.json (or any other configuration source) using the Aspire:StackExchange:Redis:DistributedCaching key:
{ "Aspire": { "StackExchange": { "Redis": { "DistributedCaching": { "ConnectionString": "localhost:6379", "DisableHealthChecks": false, "DisableTracing": false } } } }}Inline delegates. Pass an Action<StackExchangeRedisSettings> to configure settings inline, for example to disable tracing:
builder.AddRedisDistributedCache( "cache", static settings => settings.DisableTracing = true);To configure the underlying ConfigurationOptions, pass a second delegate:
builder.AddRedisDistributedCache( "cache", null, static options => options.ConnectTimeout = 3_000);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The Redis distributed caching client integration adds a health check that verifies the Redis instance is reachable and can execute commands. The health check is wired into the /health HTTP endpoint — all registered checks must pass before the app is considered ready to accept traffic.
Disable health checks via configuration:
{ "Aspire": { "StackExchange": { "Redis": { "DistributedCaching": { "DisableHealthChecks": true } } } }}Observability and telemetry
Section titled “Observability and telemetry”The client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging categories:
Aspire.StackExchange.Redis
Tracing activities:
OpenTelemetry.Instrumentation.StackExchangeRedis
Metrics are emitted through OpenTelemetry. Any telemetry feature can be disabled through the configuration options above.
Use the client
Section titled “Use the client”Inject IDistributedCache wherever you need it and use the standard ASP.NET Core caching API:
using Microsoft.Extensions.Caching.Distributed;using System.Text;
public class ExampleService(IDistributedCache cache){ public async Task SetAsync(string key, string value, CancellationToken ct = default) { var bytes = Encoding.UTF8.GetBytes(value); await cache.SetAsync(key, bytes, new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5) }, ct); }
public async Task<string?> GetAsync(string key, CancellationToken ct = default) { var bytes = await cache.GetAsync(key, ct); return bytes is null ? null : Encoding.UTF8.GetString(bytes); }}IDistributedCache also integrates transparently with ASP.NET Core session state, output caching, and Data Protection.