← Back to articles

ASP.NET Core memory cache

Part of my ASP.NET Core recipe series: using the built-in memory cache for data you don't want to fetch on every request.

Tedd

Response cache is fine for simpler operations, but sometimes you need more fine grained control. System.Runtime.Caching.MemoryCache has builtin support for in-memory cache with expiry.

Install

Install-Package System.Runtime.Caching

Implement

To register as a service add this to Startup.cs ConfigureServices:

services.AddMemoryCache();

Use

public class HomeController : Controller
{
 private readonly IMemoryCache _cache;

 public HomeController(IMemoryCache memoryCache)
 {
 _cache = memoryCache;
 }

 [HttpGet]
 public string CurrentTime()
 {
 var cacheEntry = _cache.GetOrCreate("CurrentTime", entry =>
 {
 entry.SlidingExpiration = TimeSpan.FromSeconds(10);
 return DateTime.Now.ToString();
 });

 return cacheEntry;
 }
} 

A colleague requested a more complex scenario where we need the cache to update exactly every 1 minute, since numbers from all requests to that particular API should be approximately in sync.

[HttpGet]
public string CurrentTime()
{
 var cacheEntry = _cache.GetOrCreate("CurrentTime", entry =>
 {
 // Calculate next whole minute
 var now = DateTimeOffset.Now.ToUnixTimeSeconds();
 var expires = now + 60 - (now % 60);

 entry.AbsoluteExpiration = DateTimeOffset.FromUnixTimeSeconds(expires);
 return DateTime.Now.ToString();
 });

 return cacheEntry;
} 

Written by Tedd · Oslo, Norway

Follow the journal via RSS