liveBook · Manning

AddDistributedMemoryCache

As explained in Pro ASP.NET Core 7, Tenth Edition

An ASP.NET Core service-registration method that configures an IDistributedCache implementation backed by memory.

AddDistributedMemoryCache registers an in-memory implementation of IDistributedCache with ASP.NET Core’s dependency-injection container. Despite its name, the store is local to one ASP.NET Core runtime instance, so stopping the application loses its contents and multiple instances do not share them. section 16.3.1 section 17.2.1

Use it for session storage or direct caching when simplicity matters more than persistence and cross-instance sharing. Session support still requires AddSession and UseSession; the method only supplies the session data store. section 8.2.4 section 16.3.1

Configure and choose the service according to the deployment:

  • Apply options such as SizeLimit to cap the cache at a specified number of items. section 17.2.1
  • Choose SQL Server or Redis instead when several runtime instances must access shared session or cache data. section 16.3.1 section 17.2.1

Caching a calculated response

Register the service with builder.Services.AddDistributedMemoryCache(opts => opts.SizeLimit = 200), inject IDistributedCache, and cache a calculated result with SetStringAsync. A two-minute AbsoluteExpirationRelativeToNow causes the next request after expiry to recalculate the value. section 17.2.1

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Explains registration, size limits, expiration, and deployment scope but defers the internals of cache storage.
Examples
Uses SportsStore session setup and a sum endpoint that caches calculated results with size and expiration settings.
What it assumes
Assumes familiarity with ASP.NET Core service registration and middleware while demonstrating the required session registrations.
What you can do after
Apply it via ASP.NET Core dependency injection to back sessions or IDistributedCache lookups with an in-memory store.
How it connects
Connects session state, IDistributedCache, middleware, SQL Server cache, and Redis cache.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.