ASP.NET Core Object Caching
NCache provides object caching support for ASP.NET Core applications as well.
Install NuGet Package
Install the NuGet package AspNetCore.Session.NCache Enterprise/Professional/OpenSource to your application by executing the following command in the Package Manager Console:
For Enterprise:
Install-Package NCache.Microsoft.Extensions.Caching
For Professional:
Install-Package NCache.Microsoft.Extensions.Caching.Professional
For OpenSource:
Install-Package NCache.Microsoft.Extensions.Caching.OpenSource
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.
For ASP.NET applications, NCache provides a custom method for configuring itself as a distributed cache.
The cache configurations can be added in
Appsettings.json of your application. The following example adds a section
NCacheSettings
which configures the cache name. You may change the name according to
your registered cache.
Important
Make sure that the cache specified is running.
. . .
"NCacheSettings": {
"CacheName": "demoClusteredCache",
"EnableLogs": "True",
"ExceptionsEnabled": "True"
}
. . .
Once the cache configuration has been specified, 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 connect to an instance of the NCache cache within the application with the GetCache method and proceed to perform operations over the objects stored in the cache.
Note
To utilize the APIs, include the following namespace in your application:
Alachisoft.NCache.Client
public async Task<IActionResult> Details(int id)
{
ICache _cache = CacheManager.GetCache(_appSettings.CacheName); //connect to cache in NCache
var cacheKey = string.Format("album_{0}", id);
Album album = null;
if (_cache != null)
{
album = _cache.Get<Album>(cacheKey); //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)
{
var cacheItem = new CacheItem(album);
cacheItem.SlidingExpiration = TimeSpan.AddMinutes(10);
// Add CacheItem to cache
_cache.Insert(cacheKey, cacheItem);
}
}
}
return View(album);
}
See Also
Multi-Region ASP.NET Core Session Provider for NCache
Session Storage in ASP.NET Core
ASP.NET