Advertisement
Intermediate .NET, Caching (In-Memory, Distributed & Redis)

How do you configure and use Redis as a distributed cache in ASP.NET Core with StackExchange.Redis?

Short answer

Install the Microsoft.Extensions.Caching.StackExchangeRedis package, register it via AddStackExchangeRedisCache with a connection string, then inject IDistributedCache to get/set values as byte arrays or strings (requiring manual serialization for complex objects, typically with…

Save .NET mock interview
Advertisement
AModel answer
Install the Microsoft.Extensions.Caching.StackExchangeRedis package, register it via AddStackExchangeRedisCache with a connection string, then inject IDistributedCache to get/set values as byte arrays or strings (requiring manual serialization for complex objects, typically with System.Text.Json), or use IConnectionMultiplexer directly for more advanced Redis-specific features like pub/sub or sorted sets.
builder.Services.AddStackExchangeRedisCache(options => {
    options.Configuration = builder.Configuration.GetConnectionString("Redis");
    options.InstanceName = "MyApp:";
});

// Usage
await cache.SetStringAsync("key", JsonSerializer.Serialize(data),
    new DistributedCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(30) });
Real-world example
A microservices architecture uses a shared Redis instance as the distributed cache layer for session data, feature flags, and computed aggregates, letting all services benefit from consistent, centrally-managed cache invalidation.
Likely follow-ups
  • What's the difference between using IDistributedCache versus IConnectionMultiplexer directly?
  • How does InstanceName help avoid key collisions when multiple apps share one Redis instance?
Related topics