IMemoryCache — in-memory caching.
Setup:
1builder.Services.AddMemoryCache();
Usage:
1public class ProductService(IMemoryCache cache)2{3 public async Task<Product> GetProductAsync(int id)4 {5 var key = $"product_{id}";6 if (!cache.TryGetValue(key, out Product product))7 {8 product = await _db.Products.FindAsync(id);9 var options = new MemoryCacheEntryOptions()10 .SetAbsoluteExpiration(TimeSpan.FromMinutes(5));11 cache.Set(key, product, options);12 }13 return product;14 }15}
Distributed cache:
1builder.Services.AddStackExchangeRedisCache(options =>2{3 options.Configuration = "localhost:6379";4});
Key: MemoryCache for local, Redis for distributed.