Introduction
In general terms, caching takes place where frequently-used data is stored so that the application can quickly access the data rather than accessing the data from the source. Caching can improve the performance and scalability of the application dramatically and can help us to remove the unnecessary requests to the external data sources for the data that changes infrequently.
ASP.NET Core has a rich support for caching and it supports different kinds of caching. In this article, we will talk about "In-Memory" cache. This is the simplest way of caching. In this technique, cache is stored in the memory of the local Web Server.
An in-memory cache is stored into the Server memory which is hosting the ASP.NET application. In the case of Web farm (where the application is hosted on multiple servers) or cloud hosting environments, all servers may have different values of in-memory cache. So, in-memory caching cannot be used in web farm or cloud hosting environments. For this type of environment, distributed cache is best suited.
How to configure In-Memory Caching in ASP.NET Core
To use in-memory cache in our ASP.NET Core project, first we need to add "Microsoft.Extensions.Caching.Memory" in project.json file.
Project.json
- {
- "version": "1.0.0-*",
- "buildOptions": {
- "preserveCompilationContext": true,
- "debugType": "portable",
- "emitEntryPoint": true
- },
- "dependencies": {},
- "frameworks": {
- "netcoreapp1.0": {
- "dependencies": {
- "Microsoft.NETCore.App": {
- "type": "platform",
- "version": "1.0.1"
- },
- "Microsoft.AspNetCore.Server.Kestrel": "1.0.0",
- "Microsoft.AspNetCore.Mvc": "1.0.0",
- "Microsoft.Extensions.Caching.Memory": "1.0.0"
- },
- "imports": "dnxcore50"
- }
- }
- }
Caching is a Service in ASP.NET Core, so we need to add the caching Service to the "ConfigureServices" method of Startup class.
Startup.cs
- public class Startup{
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddMvc();
- services.AddMemoryCache();
- }
- ….
- ….
- }
ASP.NET Core MVC Controller is able to request their dependencies explicitly via their constructors. We utilize the caching in our application by requesting an instance of IMemoryCache in our Controller (or middleware) constructor. In the following code snippet, I am using the controller component to handle the instance of IMemoryCache.
- public class HomeController : Controller
- {
- IMemoryCache _memoryCache;
- public HomeController(IMemoryCache memoryCache)
- {
- _memoryCache = memoryCache;
- }
- ….
- ….
- …
- }
Reading and Writing In-Memory cache
There are two methods available for reading from In-Memory cache.
- "Get this" will return the value if it exists otherwise returns "null".
- "TryGetValue" will assign the cache value to the out parameter and returns true when value exists in cache; else it returns false.
There is "Set" method available for writing the data into the cache. This method accepts a key which is used for looking up values that are data cached by the user, and a set of MemoryCacheEntryOptions.
The "MemoryCacheEntryOption" allows us to specify
- Absolute or sliding time-based cache expiration
- Caching priority
- Callbacks
- Dependencies
In the following example, I have created two Controller Action methods - one for setting the cache and the other for retrieving the cache.
HomeController.cs
- public class HomeController : Controller
- {
- ….
- ….
- …..
- [Route("home/SetCacheData")]
- public IActionResult SetCacheData()
- {
- var Time = DateTime.Now.ToLocalTime().ToString() ;
- MemoryCacheEntryOptions cacheOption = new MemoryCacheEntryOptions()
- {
-
- AbsoluteExpirationRelativeToNow = (DateTime.Now.AddMinutes(1) - DateTime.Now )
- };
-
-
- _memoryCache.Set("Time", Time, cacheOption);
- return View();
- }
- [Route("home/GetCacheData")]
- public IActionResult GetCacheData()
- {
- string Time = string.Empty;
- if(!_memoryCache.TryGetValue("Time", out Time))
- {
- Time = "Cache is expired or not available";
- }
- ViewBag.data = Time;
- return View();
- }
- ….
- ….
- ….
- }
In the method “SetCacheData”, I have defined AbsoluteExpirationRelativeToNow to one minute, so the cache will expire after one minute.
Output
We can set the following properties of "MemoryCacheEntryOptions" class to get the desired behavior of cache.
- AbsoluteExpiration - It gets or sets the absolute expiration date for the cache entry.
- AbsoluteExpirationRelativeToNow - It gets or sets an absolute expiration time, relative to current date and time.
- ExpirationTokens - It uses token instance to expire the cache entry.
- PostEvictionCallbacks - It gets or sets a callback that will be fired after the cache entry is removed from the cache.
- Priority - It gets or sets the priority for keeping the cache alive in memory during cache cleanup triggering.
- SlidingExpiration - It gets or sets the value in timespan for how long a cache entry can be inactive before removing it from the cache.
Remove data from the cache
Using "Remove" method of IMemoryCache interface, we can remove the cache from the memory.
- _memoryCache.Remove("Time");
Cache Callbacks
We can configure cache dependency. It may be dependent on other cache entries, programmatic tokens and the file system etc. We can also register the callback when cache is removed from the memory.
- MemoryCacheEntryOptions cacheOption = new MemoryCacheEntryOptions()
- {
- AbsoluteExpirationRelativeToNow = (DateTime.Now.AddMinutes(1) - DateTime.Now),
- };
- cacheOption.RegisterPostEvictionCallback(
- (key, value, reason, substate) =>
- {
- Console.Write("Cache expired!");
- });
This callback is run on the different threads from the thread on which the cache removal code is run. This callback method also provides us a reason for moving the cache value. The possible values are None, Removed, Replaced, Expired, TokenExpired and Capacity.
Summary
In-Memory cache allows us to store the data into the server memory and helps us to improve the performance of the application by removing unnecessary requests to external data sources. It is very simple to use. This approach of caching will not be used when the app is hosted on multiple servers in a web farm or cloud hosting environment.
I would recommend the following articles which provide more information about ASP.NET Core.
- Introduction To ASP.NET Core
- Build Your First ASP.NET MVC Core Application With Visual Studio Code
- Performing CRUD Operations With ASP.NET MVC Core And Entity Framework Core