.NET › Caching (In-Memory, Distributed & Redis)
What is IMemoryCache, and when is it appropriate to use for caching in ASP.NET Core?
BeginnerAnswer
IMemoryCache is a built-in in-process cache storing key-value pairs directly in the application's own memory, ideal for single-instance applications or data that's acceptable to recompute per-instance -- it's extremely fast (no network round-trip) but not shared across multiple server instances, and its contents are lost on application restart.
builder.Services.AddMemoryCache();
public class ProductService {
private readonly IMemoryCache _cache;
public ProductService(IMemoryCache cache) => _cache = cache;
public async Task<Product> GetProductAsync(int id) {
return await _cache.GetOrCreateAsync($"product-{id}", async entry => {
entry.SlidingExpiration = TimeSpan.FromMinutes(10);
return await _repository.GetByIdAsync(id);
});
}
}Real-world example A single-instance internal reporting tool caches expensive aggregate query results in IMemoryCache for 10 minutes, dramatically reducing database load for a report viewed repeatedly by the same handful of users.