What is IMemoryCache, and when is it appropriate for an ASP.NET Core application?
Short answer
IMemoryCache is a built-in in-process cache storing key-value pairs directly in the application's own memory, extremely fast since it requires no network round-trip, but not shared across multiple server instances and lost on application restart -- appropriate for…
Advertisement
AModel answer
IMemoryCache is a built-in in-process cache storing key-value pairs directly in the application's own memory, extremely fast since it requires no network round-trip, but not shared across multiple server instances and lost on application restart -- appropriate for single-instance applications or data that's cheap to recompute if lost.
builder.Services.AddMemoryCache();
public class ProductService(IMemoryCache 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.
Likely follow-ups
- What's the memory pressure risk of unbounded IMemoryCache growth?
- How does IMemoryCache behave differently across multiple load-balanced instances?
Related topics