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.
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.
- dotnet add package EasyCaching.Redis --version 0.4.0
- 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.
- public void ConfigureServices(IServiceCollection services)
- {
-
-
-
- services.AddDefaultInMemoryCacheWithFactory("inmemory");
-
-
- services.AddDefaultRedisCacheWithFactory("redis1",option =>
- {
- option.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6379));
- });
-
-
- services.AddDefaultRedisCacheWithFactory("redis2", option =>
- {
- option.DBConfig.Endpoints.Add(new ServerEndPoint("127.0.0.1", 6380));
- });
- }
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.
- [Route("api/[controller]")]
- public class ValuesController : Controller
- {
- private readonly IEasyCachingProviderFactory _factory;
-
- public ValuesController(IEasyCachingProviderFactory factory)
- {
- this._factory = factory;
- }
-
-
- [HttpGet]
- [Route("inmem")]
- public string GetInMemory()
- {
- var provider = _factory.GetCachingProvider("inmemory");
- var val = $"memory-{Guid.NewGuid()}";
- var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1));
- Console.WriteLine($"Type=InMemory,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
- return $"cached value : {res}";
- }
-
-
- [HttpGet]
- [Route("redis1")]
- public string GetRedis1()
- {
- var provider = _factory.GetCachingProvider("redis1");
- var val = $"redis1-{Guid.NewGuid()}";
- var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1));
- Console.WriteLine($"Type=redis1,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
- return $"cached value : {res}";
- }
-
-
- [HttpGet]
- [Route("redis2")]
- public string GetRedis2()
- {
- var provider = _factory.GetCachingProvider("redis2");
- var val = $"redis2-{Guid.NewGuid()}";
- var res = provider.Get("named-provider", () => val, TimeSpan.FromMinutes(1));
- Console.WriteLine($"Type=redis2,Key=named-provider,Value={res},Time:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
- return $"cached value : {res}";
- }
- }
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.
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!