Using IDistributedCache in ASP.NET Core
Using IDistributedCache in ASP.NET Core with NCache improves the scalability and efficiency of applications because it allows distributing the management of the cache in a global environment. With the implementation of the IDistributedCache interface in NCache, it becomes possible to have high-performance caching along with data integrity in multiple application servers.
Prerequisites
- Install the following NuGet packages in your application based:
- Enterprise: NCache.Microsoft.Extensions.Caching
- The cache must be running.
- The application must be connected to cache before performing the operation.
- For API details, refer to: TryGetValue, Set, AddNCacheDistributedCache.
- Make sure that the data being added is serializable.
- To ensure the operation is fail-safe, it is recommended to handle any potential exceptions within your application, as explained in Handling Failures.
- To handle any unseen exceptions, refer to the Troubleshooting section.
How to Configure NCache as a Distributed Cache Provider
To use NCache through the IDistributedCache API, you need to add cache configurations in the Appsettings.json of your application. The following IDistributedCache 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 specified cache is running.
. . .
"NCacheSettings": {
"CacheName": "demoCache",
"EnableLogs": "True",
"ExceptionsEnabled": "True"
}
. . .
Once the cache configuration has been specified, use the NCache provided custom method AddNCacheDistributedCache method in Startup.cs 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. 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. The following code snippet attempts to get the album detail based on the cache key. If the specified item is not found in the cache, it is fetched from the database and stored in the cache with an expiration of 10 minutes. If no operation is performed on this object within the next 10 minutes, it expires from the cache. Meanwhile, if it is fetched from the cache, it 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);
}
See Also
.NET: Alachisoft.NCache.Caching.Distributed namespace.