IDistributedCache — distributed caching.
Setup:
1builder.Services.AddStackExchangeRedisCache(options =>2{3 options.Configuration = "localhost:6379";4 options.InstanceName = "master";5});
Usage:
1public class ProductService(IDistributedCache cache)2{3 public async Task<Product> GetProductAsync(int id)4 {5 var key = $"product_{id}";6 var cached = await cache.GetStringAsync(key);7 if (cached != null)8 return JsonSerializer.Deserialize<Product>(cached);910 var product = await db.Products.FindAsync(id);11 await cache.SetStringAsync(key, JsonSerializer.Serialize(product));12 return product;13 }14}
Key: IDistributedCache for distributed caching.