IMemoryCache is the .NET abstraction for storing and retrieving arbitrary objects in an application's local memory. It integrates with ASP.NET Core dependency injection and exposes convenient Get and Set operations. Unlike System.Runtime.Caching.MemoryCache, it uses the ASP.NET Core dependency-injection design and is the recommended approach for ASP.NET Core applications. section 8.3
Use IMemoryCache in an ASP.NET Core API by following these steps:
- Enable the MemoryCache service, import Microsoft.Extensions.Caching.Memory, and inject an IMemoryCache instance into the controller constructor. section 8.3.2
- Build a cache key from every request parameter that affects the result, so different requests cannot reuse the wrong entry. section 8.3.3
- Call TryGetValue before querying the database; on a miss, retrieve the data with EF Core and store it with an absolute expiration. section 8.3.3
Caching filtered board games
A BoardGamesController can cache its Get result for 30 seconds. Serialize the request DTO and combine it with its type name to create the cache key. If TryGetValue finds a BoardGame[] entry, return it; otherwise query EF Core, save the result with a 30-second expiration, and return it. Breakpoints around the cache lookup and database query verify that the first request queries the database while a repeated request uses the cache. section 8.3.3
Listing 8.5 BoardGamesController: IMemoryCache
public BoardGamesController(
ApplicationDbContext context,
ILogger<BoardGamesController> logger,
IMemoryCache memoryCache) #1
{
_context = context;
_logger = logger;
_memoryCache = memoryCache; #2
}
Inspect the constructor injection pattern that stores IMemoryCache in a private read-only controller field. section 8.3.2
