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) });

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));

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"));

Part 4: Cache Invalidation Patterns

StrategyImplementation
TTL ExpirationSet Expiration time
Tag-based evictionIOutputCacheStore.EvictByTagAsync
Write-throughUpdate cache on write
Event-drivenInvalidate via MediatR notification
VISUAL STUDIO 2026 MADE EASY
Recommended Book

VISUAL STUDIO 2026 MADE EASY

Build real applications with C#, VB.NET, Python, JavaScript, C++, and .NET 10. A practical companion for mastering Visual Studio 2026 step by step.