Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Using Memory Cache in ASP.NET Core

DZone's Guide to

Using Memory Cache in ASP.NET Core

In this post we take a look at examples of how to integrate a memory cache into your ASP.NET Core application. Read on for details.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

 Configure()  ASP.NET Core has a memory based caching system similar to what we had in the 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 the application starts up.

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

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

In MVC components, we can use a constructor injection to get the cache's provider instance.

private readonly IMemoryCache _cache;

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

And here is how to use memory cache in a 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 there is a possibility that using only memory cache is not ideal for our situation. 

Distributed Memory Cache

To keep in line with other distributed memory cache providers that follow the IDistributedCache interface, there is also an implementation of memory cache that follows the same interface. The MemoryDistributedCache class is wrapped around the IMemoryCache and we can use it in the same way we would use any other distributed cache. One example of a distributed cache is a SQL Server based cache.

To use distributed memory cache, we have to add it to the application services in our Startup class.

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

To inject it into the MVC components, we use a constructor injection with the 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 the 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 a better idea as there is no need to change controllers and other parts of the application when the distributed cache provider is changed. In cloud and multi-box environments, some implementation of distributed cache is a must, as local caches on a web server are not synchronized.

Wrapping Up

Simple memory-based cache is still available on ASP.NET Core and there are two ways to use it. We can use with 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.

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
memory cache ,asp.net core ,web dev

Published at DZone with permission of Gunnar Peipman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}