ASP.NET Core memory cache

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;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Tedds blog

Subscribe now to keep reading and get access to the full archive.

Continue reading