Caching — store data for faster retrieval.
IMemoryCache (in-memory):
1// Registration2builder.Services.AddMemoryCache();34// Usage5public class ProductService6{7 private readonly IMemoryCache _cache;89 public async Task<Product> GetProductAsync(int id)10 {11 return await _cache.GetOrCreateAsync(12 $"product_{id}",13 async entry =>14 {15 entry.AbsoluteExpirationRelativeToNow =16 TimeSpan.FromMinutes(5);17 return await _repo.GetByIdAsync(id);18 });19 }20}
IDistributedCache (Redis/SQL):
1// Registration2builder.Services.AddStackExchangeRedisCache(options =>3{4 options.Configuration = "localhost:6379";5 options.InstanceName = "master_";6});78// Usage9var cachedData = await _distributedCache.GetStringAsync("key");10if (cachedData == null)11{12 cachedData = JsonSerializer.Serialize(data);13 await _distributedCache.SetStringAsync("key", cachedData);14}
Output caching (minimal APIs):
1app.MapGet("/products", async (IDbContext db) =>2{3 return await db.Products.ToListAsync();4})5.CacheOutput(TimeSpan.FromMinutes(10));