How to implement a distributed cache in ASP.Net Core

Take advantage of a distributed cache to improve the performance and scalability of your ASP.Net Core application

How to implement a distributed cache in ASP.Net Core
Thinkstock

ASP.Net Core provides support for various types of caching. In addition to in-memory caching and response caching, it provides built-in support for distributed caching. In one of my previous articles here, I discussed in-memory caching in ASP.Net Core. In this article we will examine how we can work with distributed caching in ASP.Net Core. We will discuss both supported implementations, i.e., using Redis as well as SQL Server as the cache stores.

What is a distributed cache

Distributed caches are used to improve the performance and scalability of applications. Typically, a distributed cache is shared by multiple application servers. In a distributed cache, the cached data doesn’t reside in the memory of an individual web server. Rather, this data is stored centrally so that it is available to all of the application’s servers. If any of the servers go down or stop responding, other servers will still be able to retrieve the cached data. Another advantage of a distributed cache is that the cached data survives server restarts. You can add or remove a server without impacting the cache or the cached data.

To take advantage of a distributed cache when working on ASP.NET Core applications, we will use the IDistributedCache interface. We’ll examine how the IDistributedCache interface differs from the IMemoryCache interface in the section that follows.

The IDistributedCache interface

The IDistributedCache interface used for distributed caching in .NET Core is more complex than the IMemoryCache interface used to cache data in the memory of an individual web server. Here is a look at the simpler IMemoryCache interface.

public interface IMemoryCache : IDisposable
{
    bool TryGetValue(object key, out object value);
    ICacheEntry CreateEntry(object key);
    void Remove(object key);
}

The IDistributedCache interface is designed for a web farm scenario. The IDistributedCache interface comprises a collection of synchronous and synchronous methods that enable you to add, retrieve, or remove items from a centralized cache. Here is a look at the IDistributedCache interface.

public interface IDistributedCache
{
    byte[] Get(string key);
    Task<byte[]> GetAsync(string key);
    void Set(string key, byte[] value,
      DistributedCacheEntryOptions options);
    Task SetAsync(string key, byte[] value,
      DistributedCacheEntryOptions options);
    void Refresh(string key);
    Task RefreshAsync(string key);
    void Remove(string key);
    Task RemoveAsync(string key);
}

Note that while IDistributedCache works with byte[], the framework provides necessary extension methods so that you can work with string objects as well. You can even write your own extension methods to work with custom data types if need be.

To use the IDistributedCache interface in an ASP.NET Core application, follow these steps:

  1. In the Visual Studio IDE, click on File > New > Project.
  2. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed.
  3. Specify a name for the project.
  4. Click OK to save the project.
  5. In the “New .Net Core Web Application…” window, select “Web API.”
  6. Ensure that “Enable Docker Support” is unchecked and that “No Authentication” is selected as we won’t be using either of these here.
  7. Click OK.

Select the project you just created in the Solution Explorer window. Next, add the “Microsoft.Extensions.Caching.Abstractions” NuGet package to your project. As of this writing, the latest stable version of this package is 2.0.0.

How to implement a distributed cache in .Net Core using Redis

First off, you should install the Redis package via the NuGet Package Manager console or NuGet Package Manager Window.

Install-Package Microsoft.Extensions.Caching.Redis

To enable Redis as a distributed cache store for your application, you need to take advantage of the AddDistributedCache method. Here is the syntax for configuring a distributed cache using Redis in .Net Core.

services.AddDistributedRedisCache (option =>
{
    option.Configuration ="Specify the connection string";
    option.InstanceName ="Specify the instance name";
});

Now add the following piece of code to the ConfigureService method in the Startup.cs file.

public void ConfigureServices(IServiceCollection services)
{
     services.AddMvc();
     services.AddDistributedRedisCache(option =>
     {
          option.Configuration ="localhost";
          option.InstanceName ="IDG";
     });
}

How to use the IDistributedCache interface in controller methods

The following code listing illustrates how you can use IDistributedCache to insert or retrieve data from a Redis cache in your controller methods.

public class DefaultController : Controller
{
     private readonly IDistributedCache _distributedCache;
     public HomeController(IDistributedCache distributedCache)
     {
          _distributedCache = distributedCache;
     }
     [HttpGet]
     public async Task<string> Get()
     {
          var cacheKey ="IDG";
          var data = _distributedCache.GetString(cacheKey);
          if (!string.IsNullOrEmpty(data))
          {
               return data; //returned from Cache
          }
          else
          {
                  string str ="Hello World";
                 _distributedCache.SetString(cacheKey, str);
               return str;
          }
     }
}

How to implement a distributed cache in .Net Core using SQL Server

While the Redis implementation of IDistributedCache is available in the Microsoft.Extensions.Caching.Redis NuGet package, the SQL Server implementation is available as part of  the Microsoft.Extensions.Caching.SqlServer NuGet package. So, to leverage SQL Server as the distributed cache repository, enter the following command in the NuGet Package Manager console.

Install-Package Microsoft.Extensions.Caching.SqlServer

To use SQL Server as the distributed cache, specify the following code in the ConfigureServices method.

services.AddDistributedSqlServerCache(x =>
{
    x.ConnectionString = Configuration["ConnectionStrings:Default"];
    x.SchemaName ="dbo";
    x.TableName ="IDGCache";
});

You should install the following NuGet package (CLI tool) for creating the necessary database tables to store the cached data.

Microsoft.Extensions.Caching.SqlConfig.Tools

Next you should run the following command to create the database tables for your cache store.

dotnet sql-cache create <connection string> <schema> <table>

ASP.Net Core provides an abstraction over distributed caching. As a result, regardless whether the underlying cache store in use is Redis or SQL Server, the IDistributedCache interface provides a uniform and easy-to-use API for storing and retrieving data from a distributed cache. The IDistributedCache interface can also be injected to your controllers easily using dependency injection.

Copyright © 2018 IDG Communications, Inc.