Introduction
In this article, you will learn how to use an open source library named EasyCaching to handle caching in ASP.NET Core.
What is EasyCaching?
EasyCaching is an open source caching library that contains basic usages and some advanced usages of caching which can help us to handle caching more easily!
EasyCaching's Github Page
https://github.com/catcherwong/EasyCaching
EasyCaching is mainly built for .NET Core projects. It contains four basic caching providers: In-Memory, Redis, Memcached, and SQLite.
Let's take a look at the basic usages of these four caching providers.
In-Memory Caching Provider
In-Memory caching provider is based on Microsoft.Extensions.Caching.Memory.
How to use it?
First of all, we need to create an ASP.NET Core Web API project (MVC and Razor Pages are OK as well).
Install EasyCaching.InMemory via NuGet using the following command.
Install-Package EasyCaching.InMemory
Add configuration to Startup class
- public class Startup
- {
- //...
- public void ConfigureServices(IServiceCollection services)
- {
- //other services.
- //Important step for In-Memory caching provider
- services.AddDefaultInMemoryCache();
- }
- }
Then, call the provider to handle caching.
- [Route("api/[controller]")]
- public class ValuesController : Controller
- {
- private readonly IEasyCachingProvider _provider;
- public ValuesController(IEasyCachingProvider provider)
- {
- this._provider = provider;
- }
- [HttpGet]
- public async Task<string> Get()
- {
- //Set
- this._provider.Set("demo", "123", TimeSpan.FromMinutes(1));
- //Set Async
- await this._provider.SetAsync("demo", "123", TimeSpan.FromMinutes(1));
- //Get
- var res = this._provider.Get("demo", () => "456", TimeSpan.FromMinutes(1));
- //Get Async
- var res = await this._provider.GetAsync("demo",async () => await Task.FromResult("456"), TimeSpan.FromMinutes(1));
- //Get without data retriever
- var res = this._provider.Get<string>("demo");
- //Get without data retriever Async
- var res = await this._provider.GetAsync<string>("demo");
- //Refresh
- this._provider.Refresh("key", "123", TimeSpan.FromMinutes(1));
- //Refresh Async
- await this._provider.RefreshAsync("key", "123", TimeSpan.FromMinutes(1));
- //Remove
- this._provider.Remove("demo");
- //Remove Async
- await this._provider.RemoveAsync("demo");
- return "OK";
- }
- }

Sagar Pandurang KapPosted Feb 5, 2018, 10:20 PM
Very good description......