How to use In Memory Cache in ASP.NET Core?
Today I got one question regarding caching in .NET Core, so I thought why not to provide a small detail about how to use In Memory Cache in ASP.NET Core 2.x. In .NET Core, it's easy to use caching with the help of Middleware. If you want to know more about Middleware then visit https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-2.1
So how to use In Memory Cache in ASP.NET Core? In order to use In Memory Cache in ASP.NET Core, first, we need to have a NuGet Package i.e. Microsoft.Extensions.Caching.Memory we can install it directly with NuGet Package Manager in Visual Studio or with NPM Console or Directly add/edit in Project.csproj file in like.
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="2.1.2" />
</ItemGroup>
An Image with NuGet Package Manager is shown below,
So once you got NuGet Package now next step is to add a Middleware from startup.cs in ConfigureServices section, just after services.AddMvc() line like
services.AddMemoryCache();
Now setup part is done now where we want to do In Memory Cache we just have to initialize it and set the value in In Memory Cache and we can get it where we need it.
An Example of Initialization in Home Controller is given below,
//A Deceleration
IMemoryCache _memoryCache;
//Initialization in a constructor of Home Controller
public HomeController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}
Now to set and get value from In Memory Cache I just created a dummy method for getting a list of projects. So a method will return list of the project from In Memory Cache if it is not null else it will get data from the database and set it in In Memory Cache and return a project list.This method has async signature as .NET Core supports well async, but it is not necessary to use async in In Memory Cache it's up to your need. In the above method, I retrieved data from the database with async method so I just added it async.
private async Task<List<ProjectInfo>> GetProjectList()
{
MemoryCacheEntryOptions cacheOption = new MemoryCacheEntryOptions()
{
//As per your application logic you set a time for Caching
//For this example I had created Cache duration of 30 minutes
AbsoluteExpirationRelativeToNow = (DateTime.Now.AddMinutes(30) - DateTime.Now)
};
List<ProjectInfo> objProjectList;
//if Cache key is not null then get data from cache else load data from database and set into cache so that it is usable for next time
if (_memoryCache.Get("ProjectList") != null)
{
objProjectList = (List<ProjectInfo>)_memoryCache.Get("ProjectList");
}
else
{
GenralCRUD objCRUID = new GenralCRUD();
//Get List of Projects from Database, as we all know how to get data fraom database that section is excluded from this article scope.
objProjectList = await objCRUID.GetProjectList();
_memoryCache.Set("ProjectList", objProjectList, cacheOption);
}
return objProjectList;
}
Note:- Be sure that a data that you want to store in a cache can be stored in Server memory, if you do not have enough memory then it can result in a bad performance for your application as this caching data is stored in server memory and it's always finite in nature.
So it's a very cool feature of .NET Core to use In Memory Cache with just a few small setups and you have done it. Hope you like.