इसे छोड़कर कंटेंट पर जाएं
Docs Try Aspire
Docs Try

Connect to Redis distributed caching

यह कंटेंट अभी तक आपकी भाषा में उपलब्ध नहीं है।

Redis logo

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.

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 NameEnvironment variableDescription
HostCACHE_HOSTThe hostname or IP address of the Redis server
PortCACHE_PORTThe port number the Redis server is listening on
PasswordCACHE_PASSWORDThe password for authentication
UriCACHE_URIThe full connection URI: redis://:{Password}@{Host}:{Port}

Example connection string:

CACHE_URI=redis://:p%40ssw0rd1@localhost:6379

The Aspire.StackExchange.Redis.DistributedCaching client integration reads these values automatically; you don’t need to read environment variables directly.

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 📦 Aspire.StackExchange.Redis.DistributedCaching NuGet package in the client-consuming project:

.NET CLI — Add Aspire.StackExchange.Redis.DistributedCaching package
dotnet add package Aspire.StackExchange.Redis.DistributedCaching

In Program.cs, call AddRedisDistributedCache on your IHostApplicationBuilder to register an IDistributedCache backed by Redis:

C# — Program.cs
builder.AddRedisDistributedCache(connectionName: "cache");

Resolve IDistributedCache through dependency injection:

C# — ExampleService.cs
public class ExampleService(IDistributedCache cache)
{
// Use 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:

C# — Program.cs
builder.AddKeyedRedisClient(name: "chat");
builder.AddKeyedRedisDistributedCache(name: "product");

Resolve the instances separately:

C# — ExampleService.cs
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
}

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:

C# — Program.cs
builder.AddRedisDistributedCache("cache");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"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:

JSON — appsettings.json
{
"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:

C# — Program.cs
builder.AddRedisDistributedCache(
"cache",
static settings => settings.DisableTracing = true);

To configure the underlying ConfigurationOptions, pass a second delegate:

C# — Program.cs
builder.AddRedisDistributedCache(
"cache",
null,
static options => options.ConnectTimeout = 3_000);

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:

JSON — appsettings.json
{
"Aspire": {
"StackExchange": {
"Redis": {
"DistributedCaching": {
"DisableHealthChecks": true
}
}
}
}
}

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.

Inject IDistributedCache wherever you need it and use the standard ASP.NET Core caching API:

C# — ExampleService.cs
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.