Using memory cache in ASP.NET Core

ASP.NET Core has memory based caching similar to what we had in previous ASP.NET versions. This blog post shows how to use memory cache alone and with support for distributed cache in ASP.NET Core web applications.

Using memory cache

Using memory cache starts with adding caching support to services when application starts up.

public void ConfigureServices(IServiceCollection services)
{                       
    services.AddLogging();
    services.AddMemoryCache();

    services.AddMvc();
}

As caching has nothing to do with request pipeline we don’t have to update Configure() method of start-up class.

In MVC components we can use constructor injection to get cache provider instance.

private readonly IMemoryCache _cache;

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

And here is how to use memory cache in controller.

public class HomeController : Controller
{
   
private readonly IMemoryCache
_cache;

   
public HomeController(IMemoryCache
cache)
    {
        _cache = cache;
    }
   
public IActionResult
Index()
    {
        _cache.Set(
"TestKey", "MyValue"
);

       
var value = _cache.Get<string>("TestKey"
);
       
       
return View();
    }
}

But it is possible we don’t want to use only memory cache.

Distributed memory cache

To keep in line with other distributed memory cache providers that follow IDistributedCache interface there is also implementation of memory cache that follows the same interface. MemoryDistributedCache class is wrapper around IMemoryCache and we can use it as any other distributed cache. One example of sitributed cache is SQL Server based cache.

To use distributed memory cache we have to add it to application services in Startip class.

public void ConfigureServices(IServiceCollection services)
{                       
    services.AddLogging();
    services.AddDistributedMemoryCache();

    services.AddMvc();
}

To inject it to MVC components we use constructor injection with IDistributedCache interface. In controllers and view components we will use it as any other distributed cache service.

public class HomeController : Controller
{
   
private readonly IDistributedCache
_cache;

   
public HomeController(IDistributedCache
cache)
    {
        _cache = cache;
    }
   
public IActionResult
Index()
    {
        _cache.SetString(
"TestKey", "MyValue"
);

       
var value = _cache.GetString("TestKey"
);
       
       
return View();
    }
}

Memory cache or distributed memory cache?

Using memory cache is the option for systems running on single box. Also in development environments we could prefer memory based cache to keep external services away when building the system. I think that going with IDistributedCache is better idea as there is no need for changes in controllers and other parts of application when distributed cache provider is changed. In cloud and multi-box environments some implementation of distributed cache is a must as local caches on web server are not synchronized.

Wrapping up

Simple memory-based cache is still available on ASP.NET Core and there are two ways how to use it. We can use it by IMemoeyCache interface and have only memory based cache supported or we can go with IDistributedCache interface and have many other cache providers supported. For cloud and clusters IDistributedCache is preferred as local caches of web servers are not synchronized.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    3 thoughts on “Using memory cache in ASP.NET Core

    • January 30, 2018 at 5:56 pm
      Permalink

      Great article, thanks!

      But I’m confused that all controllers will use same cache instance. Lets imagine we want to keep to different types of objects.
      Should we create two instances per object type?
      What are pros/cons of having multiple instances of MemoryCache within same web app?
      What are pros/cons of having one instance of MemoryCache within same web app?

    • February 1, 2018 at 6:23 am
      Permalink

      You need only one instance of cache and it works with different types of objects as every object has different key. It’s also possible to use multiple instances of cache but it is rare situation.

    • September 12, 2018 at 9:27 am
      Permalink

      System.NullReferenceException: ‘Object reference not set to an instance of an object.’
      cache.Set(“TestKey”, “MyValue”); I got error this line.

    Leave a Reply

    Your email address will not be published. Required fields are marked *