Caching in ASP.NET Core MVC and Web API
Caching: There are many ways to improve the performance of an application. Caching is one of the ways to improve application performance and optimise data retrieval from various sources. In caching, we store frequently used data in local storage, called the cache, for some time, and serve it from the cache when needed. This reduces database operations and gives the application data quickly. It minimises the database load and improves the response time.
Types of Caching in ASP.NET Core
There are three main types of caching in ASP.NET Core:
- In-Memory Caching: Data is stored in the memory of the web server. It is fast and simple to implement, but limited by the server's memory. It is suitable for lightweight applications that run as a single instance.
- Distributed Caching: As the name suggests, one common cache is shared across multiple servers. Sharing the cache reduces the memory needed on each server and provides fast access to cached data. It is widely used in microservices architectures, where the application is deployed on more than one server. Nowadays, SQL Server and Redis are the popular choices for distributed caching in ASP.NET Core.
- Response Caching: Response caching deals with the response we get from an HTTP request. It stores responses in the cache and is widely used in Web APIs and web applications.
The image below explains the caching process, showing data retrieval with and without caching. Without caching, you have to make more database calls: here, three users make three separate calls to fetch employee data from the database. The application makes three database calls for the same data, which increases processing time and reduces performance. With caching, the employee data is stored in local storage called the cache, and all three users get the data from the cache. This gives fast access to the data and reduces the number of database calls.
How to Implement Caching in .NET Core
In-Memory Cache Implementation
For the in-memory cache, I created an interface named ICacheService that declares a GetAsync method with three parameters: the cache key, a Task and a TimeSpan, as you can see in the image below.
public interface ICacheService
{
Task<T> GetAsync<T>(string cacheKey,Task<T> DataRetrieval,TimeSpan? slidingExipartion=null);
}
Create a class InMemoryCachedServices that implements ICacheService, so it must provide the GetAsync method. In its constructor, assign the private readonly field for the IMemoryCache interface. IMemoryCache provides the built-in caching methods. Check whether the data is already in the cache using the TryGetValue method. If it is not, fetch it from the server and save it in the cache for a duration defined with MemoryCacheEntryOptions. If cached data exists, it is returned from the cache; otherwise the data is fetched from the server, stored in the cache and returned to the user.
public class InMemoryCachedServices :ICacheService
{
private readonly IMemoryCache cache;
public InMemoryCachedServices(IMemoryCache _cache)
{
cache = _cache;
}
public async Task<T> GetAsync<T>(string cacheKey,
Task<T> DataRetrieval,
TimeSpan? slidingExipartion = null)
{
if(!cache.TryGetValue(cacheKey, out T cachedata))
{
cachedata=await DataRetrieval;
var cacheEntriOptions = new MemoryCacheEntryOptions
{
SlidingExpiration= slidingExipartion ?? TimeSpan.FromMinutes(1),
};
cache.Set(cacheKey, cachedata, cacheEntriOptions);
}
return cachedata;
}
}
For caching, we register the caching services in the application's Program.cs file. Here I added AddMemoryCache(), and we also register the interface and service class that contain the cache code, so they can be injected into the EmployeeController. Below is the code for the Program.cs file.
builder.Services.AddMemoryCache();
builder.Services.AddScoped<ICacheService,InMemoryCachedServices>();
After registering the services in Program.cs, I created an EmployeeController with a constructor that receives its dependencies, so we can use them in the controller. Here I injected ICacheService and ILogger. I created an action method, GetEmployeeList(), that returns the employee list in the response, as shown in the code below. I also log the HTTP requests to a log file, so we can evaluate the caching in more detail.
public class EmployeeController : ControllerBase
{
private readonly IEmployeeRepo _empService;
private readonly ILogger<EmployeeController> _logger;
private readonly ICacheService _cache;
public EmployeeController(IEmployeeRepo empService,
ILogger<EmployeeController> logger,
ICacheService cache)
{
_empService = empService;
_logger = logger;
_cache = cache;
}
[HttpGet("getemployeelist")]
public async Task<List<Employee>> GetEmployeeList()
{
try
{
_logger.LogInformation("Requesting Employee List Details...");
var keyForCache = "employeeList";
List<Employee> employeeList= await _cache.GetAsync(keyForCache, _empService.GetEmployeeListAsync(),
TimeSpan.FromMinutes(1));
_logger.LogInformation("Employee List Details fetched...");
return employeeList;
}
catch
{ throw;
}
}
}
As you can see in the image below, the first request takes 13 seconds to fetch data from the server, and the second request takes only 4 seconds because it gets the data from the cache, so it has a lower execution and response time.