Skip to main content

Overview

The Aspire.StackExchange.Redis component registers an IConnectionMultiplexer in your dependency injection container for connecting to Redis servers. It automatically enables health checks, logging, and distributed tracing.

Installation

Install the component using the .NET CLI:
dotnet add package Aspire.StackExchange.Redis

Usage

Register the component

In your service’s Program.cs file, call the AddRedisClient extension method:
builder.AddRedisClient("cache");

Inject and use the connection multiplexer

Retrieve the IConnectionMultiplexer instance using dependency injection:
public class ProductsController : ControllerBase
{
    private readonly IConnectionMultiplexer _redis;

    public ProductsController(IConnectionMultiplexer redis)
    {
        _redis = redis;
    }

    [HttpGet("{id}")]
    public async Task<IActionResult> GetProduct(int id)
    {
        var db = _redis.GetDatabase();
        var cacheKey = $"product:{id}";
        
        // Try to get from cache
        var cachedProduct = await db.StringGetAsync(cacheKey);
        if (cachedProduct.HasValue)
        {
            return Ok(JsonSerializer.Deserialize<Product>(cachedProduct));
        }
        
        // Fetch from database and cache
        var product = await FetchProductFromDatabase(id);
        await db.StringSetAsync(cacheKey, 
            JsonSerializer.Serialize(product),
            TimeSpan.FromMinutes(10));
        
        return Ok(product);
    }
}

Configuration

The component provides multiple configuration options based on your project requirements.

Connection string

Provide a connection string in your appsettings.json:
{
  "ConnectionStrings": {
    "cache": "localhost:6379"
  }
}
Then register the component using the connection name:
builder.AddRedisClient("cache");
For more information on connection string format, see the StackExchange.Redis configuration documentation.

Configuration providers

Configure component settings using the Aspire:StackExchange:Redis configuration section:
{
  "Aspire": {
    "StackExchange": {
      "Redis": {
        "ConfigurationOptions": {
          "ConnectTimeout": 3000,
          "ConnectRetry": 2
        },
        "DisableHealthChecks": true,
        "DisableTracing": false
      }
    }
  }
}

Inline configuration

Configure settings directly in code using a delegate:
builder.AddRedisClient("cache", settings => 
{
    settings.DisableHealthChecks = true;
});
You can also configure the ConfigurationOptions:
builder.AddRedisClient("cache", 
    configureOptions: options => 
    {
        options.ConnectTimeout = 3000;
        options.ConnectRetry = 2;
    });

AppHost integration

In your AppHost project, install the Redis hosting package:
dotnet add package Aspire.Hosting.Redis
Register a Redis server in your AppHost’s Program.cs:
var redis = builder.AddRedis("cache");

var myService = builder.AddProject<Projects.MyService>()
                       .WithReference(redis);
The WithReference method automatically configures the connection string in your service. Consume it in your service’s Program.cs:
builder.AddRedisClient("cache");
The connection name passed to WithReference must match the name used in AddRedisClient.

Configuration options

The following settings are available:
SettingDescriptionDefault
DisableHealthChecksDisable automatic health check registrationfalse
DisableTracingDisable OpenTelemetry tracingfalse
ConfigurationOptionsConfigure StackExchange.Redis optionsnull

Health checks

The component automatically registers a health check that verifies the Redis connection. The health check:
  • Pings the Redis server
  • Verifies connectivity
  • Reports the status in the /health endpoint
You can disable health checks by setting DisableHealthChecks to true.

Observability

Logging

The component integrates with .NET logging to provide:
  • Connection events
  • Command execution information
  • Error details

Tracing

Distributed tracing captures:
  • Redis operations
  • Command execution time
  • Connection activity
Traces appear in the Aspire dashboard and integrate with OpenTelemetry collectors.

Common scenarios

Caching

Use Redis as a distributed cache:
public async Task<Product> GetProductAsync(int id)
{
    var db = _redis.GetDatabase();
    var key = $"product:{id}";
    
    var cached = await db.StringGetAsync(key);
    if (cached.HasValue)
    {
        return JsonSerializer.Deserialize<Product>(cached);
    }
    
    var product = await _productRepository.GetByIdAsync(id);
    await db.StringSetAsync(key, 
        JsonSerializer.Serialize(product),
        TimeSpan.FromMinutes(10));
    
    return product;
}

Pub/Sub messaging

Use Redis for publish/subscribe messaging:
public class NotificationService
{
    private readonly IConnectionMultiplexer _redis;

    public NotificationService(IConnectionMultiplexer redis)
    {
        _redis = redis;
    }

    public async Task PublishNotification(string channel, string message)
    {
        var subscriber = _redis.GetSubscriber();
        await subscriber.PublishAsync(channel, message);
    }

    public async Task SubscribeToNotifications(string channel)
    {
        var subscriber = _redis.GetSubscriber();
        await subscriber.SubscribeAsync(channel, (ch, message) =>
        {
            Console.WriteLine($"Received: {message}");
        });
    }
}

Distributed locks

Implement distributed locks:
public async Task<bool> AcquireLockAsync(string resource, TimeSpan expiry)
{
    var db = _redis.GetDatabase();
    var lockKey = $"lock:{resource}";
    var token = Guid.NewGuid().ToString();
    
    return await db.StringSetAsync(lockKey, token, expiry, When.NotExists);
}

Session storage

Store session data in Redis:
public async Task SaveSessionAsync(string sessionId, UserSession session)
{
    var db = _redis.GetDatabase();
    var key = $"session:{sessionId}";
    
    await db.StringSetAsync(key,
        JsonSerializer.Serialize(session),
        TimeSpan.FromHours(1));
}

Best practices

The IConnectionMultiplexer is designed to be reused throughout your application. Never create multiple instances - use dependency injection to share a single instance.
Redis supports multiple data types (strings, hashes, lists, sets, sorted sets). Choose the appropriate type for your use case:
// String for simple values
await db.StringSetAsync("key", "value");

// Hash for objects
await db.HashSetAsync("user:1", new HashEntry[] 
{
    new HashEntry("name", "John"),
    new HashEntry("age", "30")
});

// List for ordered collections
await db.ListRightPushAsync("queue", "item");
Always set expiration times for cache entries to prevent memory exhaustion:
await db.StringSetAsync(key, value, TimeSpan.FromMinutes(10));
Implement fallback logic for when Redis is unavailable:
try
{
    var cached = await db.StringGetAsync(key);
    if (cached.HasValue) return cached;
}
catch (RedisException)
{
    // Log and continue without cache
}

return await FetchFromDatabase();
Use batching to reduce round trips:
var batch = db.CreateBatch();
var tasks = new List<Task>();

foreach (var item in items)
{
    tasks.Add(batch.StringSetAsync(item.Key, item.Value));
}

batch.Execute();
await Task.WhenAll(tasks);

Additional resources

PostgreSQL

Connect to PostgreSQL databases

MongoDB

Work with MongoDB databases

Azure Cosmos DB

Connect to Azure Cosmos DB

Redis Hosting

Learn about the Redis hosting integration

Build docs developers (and LLMs) love