liveBook · Manning

IMemoryCache

As explained in Building Web APIs with ASP.NET Core

IMemoryCache is the .NET abstraction for storing and retrieving objects in an application's memory cache.

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

How Building Web APIs with ASP.NET Core covers it

How deep it goes
Explains dependency injection, key construction, cache lookup, expiration, and verification, but not cache internals.
Examples
Demonstrates cached BoardGamesController results, serialized request keys, 30-second expiration, and breakpoint-based verification.
What it assumes
Assumes familiarity with ASP.NET Core dependency injection, controllers, DTOs, and EF Core queries.
What you can do after
Build it from scratch by injecting IMemoryCache and implementing parameter-aware cache-or-query logic.
How it connects
Connects dependency injection, ASP.NET Core, EF Core, response caching, and distributed caching.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Building Web APIs with ASP.NET Core. The section links point to the parts of the book it draws on.