Section 1 of 6
In-Memory Caching
🎯 What You'll Learn
- What is caching
- IMemoryCache interface
- Setting cache entries
- Cache expiration
- Cache eviction
What is Caching?
Caching stores frequently accessed data in memory to avoid expensive operations like database queries or API calls.
Setup
Program.cs
C#
builder.Services.AddMemoryCache();
Using IMemoryCache
Inject IMemoryCache
C#
public class ProductsController : Controller
{
private readonly IMemoryCache _cache;
public ProductsController(IMemoryCache cache)
{
_cache = cache;
}
}
Setting and Getting Cache
Basic Caching
C#
// Set cache
_cache.Set("products", products);
// Get cache
if (_cache.TryGetValue("products", out List<Product> cachedProducts))
{
return cachedProducts;
}
GetOrCreate Pattern
GetOrCreate
C#
var products = _cache.GetOrCreate("products", entry =>
{
entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
return _context.Products.ToList();
});
Cache Expiration
Absolute Expiration
Cache expires at a specific time.
Absolute Expiration
C#
_cache.Set("products", products, new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10)
});
Sliding Expiration
Cache expires if not accessed within the time window.
Sliding Expiration
C#
_cache.Set("products", products, new MemoryCacheEntryOptions
{
SlidingExpiration = TimeSpan.FromMinutes(5)
});
Cache Eviction
Remove from Cache
C#
_cache.Remove("products");
InvenTrack Example
ProductsController.cs
C#
public class ProductsController : Controller
{
private readonly IMemoryCache _cache;
private readonly InvenTrackDbContext _context;
[HttpGet]
public async Task<IActionResult> Index()
{
const string cacheKey = "products_list";
// Try get from cache
if (!_cache.TryGetValue(cacheKey, out List<Product> products))
{
// Not in cache, fetch from database
products = await _context.Products.ToListAsync();
// Set cache with 5 minute expiration
var cacheOptions = new MemoryCacheEntryOptions
{
AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5),
SlidingExpiration = TimeSpan.FromMinutes(2)
};
_cache.Set(cacheKey, products, cacheOptions);
}
return View(products);
}
[HttpPost]
public async Task<IActionResult> Create(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
// Invalidate cache
_cache.Remove("products_list");
return RedirectToAction("Index");
}
}
Key Takeaways
- Caching: Store data in memory for fast access
- AddMemoryCache(): Register caching service
- IMemoryCache: Inject to use caching
- Set()/Get(): Store and retrieve data
- GetOrCreate(): Get or create if missing
- Absolute expiration: Expires at specific time
- Sliding expiration: Expires if not accessed
- Remove(): Invalidate cache