Handling Multiple Instances Of Caching Providers Using EasyCaching

Background

Most of the time, we may use one type of caching in our projects, such as Redis or InMemory etc. However, we may often need two or three types of caching depending on the requirement of our project. In this article, I will show you how to solve this problem of multiple caching needs by using EasyCahing with ASP.NET Core.
 
For more information about EasyCaching, you can follow my past articles about it or visit its GitHub page.
 
Now, let's begin.
 
Solution
 
We are using IEasyCachingProviderFactory to get the caching providers that you want to use. We shall install the latest version (this time, it is v0.4.0) of EasyCaching here because it incorporates the new features of EasyCaching. Add InMemory and Redis - the two providers into your project. 
  1. dotnet add package EasyCaching.Redis --version 0.4.0  
  2. dotnet add package EasyCaching.InMemory --version 0.4.0  
Before we use it, we need to configure it in the Startup class. Here, we will use two types of caching providers with three instances - one in-memory caching provider and two Redis caching providers.
  1. public void ConfigureServices(IServiceCollection services)  
  2. {  
  3.     //other ..  
  4.       
  5.     //configure the in-memory caching provider  
  6.     services.AddDefaultInMemoryCacheWithFactory("inmemory");  
  7.   
  8.     //configure the first redis caching provider  
  9.     services.AddDefaultRedisCacheWithFactory("redis1",option =>  
  10.     {  
  11.         option.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379));  
  12.     });  
  13.   
  14.     //configure the second redis caching provider  
  15.     services.AddDefaultRedisCacheWithFactory("redis2", option =>  
  16.     {  
  17.         option.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6380));  
  18.     });  
  19. }  
Note 
Here, we used AddDefaultInMemoryCacheWithFactory and AddDefaultRedisCacheWithFactory to replace the AddDefaultInMemoryCache and AddDefaultRedisCache respectively.This is an important step to deal with factory. 
 
After configuring the factory, we can use it via dependency injection where we need to use. For example, the following code shows how to use IEasyCachingProviderFactory in the controller.
  1. [Route("api/[controller]")]  
  2. public class ValuesController : Controller  
  3. {  
  4.     private readonly IEasyCachingProviderFactory _factory;  
  5.   
  6.     public ValuesController(IEasyCachingProviderFactory factory)  
  7.     {  
  8.         this._factory = factory;  
  9.     }  
  10.   
  11.     // GET api/values/inmem  
  12.     [HttpGet]  
  13.     [Route("inmem")]  
  14.     public string GetInMemory()  
  15.     {  
  16.         var provider = _factory.GetCachingProvider("inmemory");  
  17.         var val = $"memory-{Guid.NewGuid()}";  
  18.         var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1));  
  19.         Console.WriteLine($"Type=InMemory,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");  
  20.         return $"cached value : {res}";                 
  21.     }  
  22.   
  23.     // GET api/values/redis1  
  24.     [HttpGet]  
  25.     [Route("redis1")]  
  26.     public string GetRedis1()  
  27.     {  
  28.         var provider = _factory.GetCachingProvider("redis1");  
  29.         var val =  $"redis1-{Guid.NewGuid()}";  
  30.         var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1));  
  31.         Console.WriteLine($"Type=redis1,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");  
  32.         return $"cached value : {res}";  
  33.     }  
  34.       
  35.     // GET api/values/redis2  
  36.     [HttpGet]  
  37.     [Route("redis2")]  
  38.     public string GetRedis2()  
  39.     {  
  40.         var provider = _factory.GetCachingProvider("redis2");  
  41.         var val =  $"redis2-{Guid.NewGuid()}";  
  42.         var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1));  
  43.         Console.WriteLine($"Type=redis2,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");  
  44.         return $"cached value : {res}";  
  45.     }  
  46. }  
GetCachingProvider is the key method to get the registered caching providers via their name. This name must be the same as what we registered in the configuration.
 
If we pass a not registered or not existed caching provider name to this method, it will throw an exception with a message to tell us that it can not find a matching caching provider!
 
Now, let's take a look at the result when we visit those three APIs.
 
Using EasyCaching To Handle Multiple Instance Of Caching Providers 
 
We visited http://localhost:9999/api/values/inmem, http://localhost:9999/api/values/redis1, and http://localhost:9999/api/values/redis2 one by one.
 
The first time, all the cached values will be initialized.
 
The second time, all the cached values were the same as the first time because they're still valid.
 
The third time, after the expiration, all the cached values were changed!
 
The result tells us that all the caching providers will not affect others.

Summary

In this article, I showed you how to handle multiple instances of caching providers when using EasyCaching in your ASP.NET Core project!

The way to get a caching provider is similar to creating a new instance of HttpClient via HttpClientFactory.
 
I hope this article can help you!