Lesson 24 of 40
Performance
Intermediate
35 min
Caching Strategies
Implement multi-layer caching with IMemoryCache, IDistributedCache, Redis, output caching, and the new HybridCache in .NET 10.
Part 1: HybridCache (.NET 10)
HybridCache combines in-process L1 cache with distributed L2 cache automatically:
builder.Services.AddHybridCache();
// Usage
var result = await _cache.GetOrCreateAsync(
$"order:{id}",
async ct => await _db.GetOrderAsync(id, ct),
new() { Expiration = TimeSpan.FromMinutes(10) });
// Usage
var result = await _cache.GetOrCreateAsync(
$"order:{id}",
async ct => await _db.GetOrderAsync(id, ct),
new() { Expiration = TimeSpan.FromMinutes(10) });
Part 2: Redis with StackExchange
builder.Services.AddStackExchangeRedisCache(o =>
o.Configuration = builder.Configuration["Redis:ConnectionString"]);
// For complex scenarios, use IConnectionMultiplexer directly
builder.Services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect(redisConfig));
o.Configuration = builder.Configuration["Redis:ConnectionString"]);
// For complex scenarios, use IConnectionMultiplexer directly
builder.Services.AddSingleton<IConnectionMultiplexer>(
ConnectionMultiplexer.Connect(redisConfig));
Part 3: Output Caching
Cache entire HTTP responses with Output Caching:
app.MapGet("/api/products", async (IProductService svc) =>
await svc.GetAllAsync())
.CacheOutput(p => p.Expire(TimeSpan.FromMinutes(5))
.Tag("products"));
await svc.GetAllAsync())
.CacheOutput(p => p.Expire(TimeSpan.FromMinutes(5))
.Tag("products"));
Part 4: Cache Invalidation Patterns
| Strategy | Implementation |
|---|---|
| TTL Expiration | Set Expiration time |
| Tag-based eviction | IOutputCacheStore.EvictByTagAsync |
| Write-through | Update cache on write |
| Event-driven | Invalidate via MediatR notification |