Object Caching in ASP.NET Core
NCache provides object caching support for ASP.NET Core applications as well.
Install NuGet Package
Install the NuGet package Alachisoft.NCache.SessionServices to your application by executing the following command in the Package Manager Console:
Install-Package Alachisoft.NCache.SessionServices
Using NCache Distributed Caching
Let’s suppose our database contains information for a music store, including album information, genre, artist, order details and so on. We proceed to fetch the details for an album, which is stored as an object of the Album class.
In Startup.cs, use the AddNCacheDistributedCache()
method to set NCache as
the default cache for storing objects.
public void ConfigureServices(IServiceCollection services)
{
services.AddNCacheDistributedCache(Configuration.GetSection("NCacheSettings"));
}
NCache is now the underlying cache for IDistributedCache. The following code snippet attempts to get the album detail based on the cache key, where if there is no item existing in the cache, the item is fetched from the database.
If the album is retrieved from the database, it is stored in NCache with expiry value of 10 minutes. If the object is not fetched from the cache within the next 10 minutes, it is expired from the cache.
If the object is fetched successfully, the object is returned as an object of Album.
public async Task<IActionResult> Details(
[FromServices] IDistributedCache cache,
int id)
{
var cacheKey = string.Format("album1", id);
Album album;
object value;
if (!cache.TryGetValue(cacheKey, out value)){
album = await DbContext.Albums
.Where(a => a.AlbumId == id)
.Include(a => a.Artist)
.Include(a => a.Genre)
.FirstOrDefaultAsync();
if (album != null){
if (_appSettings.CacheDbResults){
//Remove it from cache if not retrieved in last 10 minutes
cache.SetObject(cacheKey, album, new DistributedCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromMinutes(10)));
}
}
}
else {
album = value as Album;
}
if (album == null){
return NotFound();
}
return View(album);
}
}
Using NCache for Object Caching in ASP.NET Core
You can initialize an instance of the NCache cache within the application with
the InitializeCache()
method and proceed to perform operations over the objects
stored in the cache.
To utilize the APIs, include the following namespace in your application:
Alachisoft.NCache.Web.Caching
public async Task<IActionResult> Details(int id)
{
_cache = NCache.InitializeCache(_appSettings.CacheName); //initialize cache in NCache
var cacheKey = string.Format("album_{0}", id);
Album album = null;
if (_cache != null){
album = _cache.Get(cacheKey) as Album; //fetch Album object
}
if (album == null)
{
album = await DbContext.Albums
.Where(a => a.AlbumId == id)
.Include(a => a.Artist)
.Include(a => a.Genre)
.FirstOrDefaultAsync();
if (album != null){
if (_appSettings.CacheDbResults && _cache != null){
//Remove it from cache if not retrieved in last 10 minutes
_cache.Insert(cacheKey, album, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(10),
Alachisoft.NCache.Runtime.CacheItemPriority.Default);
}
}
}
return View(album);
}
See Also
Multi-Region ASP.NET Core Session Provider for NCache