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
