Although ASP.Net Core lacks a cache object, it provides support for several different types of caching including in-memory caching, distributed caching, and response caching. An open-source product provided by Alachisoft, NCache is an extremely fast, in-memory, distributed, scalable caching framework for use in .Net applications.
NCache is 100-percent native .Net. It is not only faster than Redis, but also provides several distributed caching features that are not supported by Redis. You can learn more about the differences between NCache and Redis here. This article will discuss how we can work with NCache in ASP.Net Core applications.
Create an ASP.Net Core project in Visual Studio
First off, let’s create an ASP.Net Core project. If Visual Studio 2017 is up and running in your system, follow the steps given below to create a new ASP.Net Core project in Visual Studio.
- Launch the Visual Studio 2017 IDE.
- Click on File > New > Project.
- Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates displayed.
- Specify a name for the project.
- Click OK to save the project.
- A new window “New .Net Core Web Application…” is shown next.
- Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
- Select API as the project template
- Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
- Ensure that “No Authentication” is selected as we won’t be using authentication either.
- Click OK.
You should now have a new ASP.Net Core project ready to go in Visual Studio. Next, you will need to install the necessary NuGet package for using NCache. Install the following NuGet package via the NuGet Package Manager window or from the NuGet Package Manager console:
Alachisoft.NCache.SessionServices
Once this NuGet package is installed in your project, you are all set to use NCache.
Use the IDistributedCache interface in ASP.Net Core
To use a distributed cache in ASP.Net Core applications, you should use the IDistributedCache interface. The IDistributedCache interface was introduced in ASP.Net Core to enable you to easily plug in third-party caching frameworks. Here is what the IDistributedCache looks like.
namespace Microsoft.Extensions.Caching.Distributed
{
public interface IDistributedCache
{
byte[] Get(string key);
void Refresh(string key);
void Remove(string key);
void Set(string key, byte[] value,
DistributedCacheEntryOptions options);
}
}
Configure NCache as an IDistributedCache provider in ASP.Net Core
To work with distributed caching using NCache, you should make a call to the AddNCacheDistributedCache method in the ConfigureServices method of the Startup.cs file as shown in the code snippet below. Note that the AddNCacheDistributedCache() method is an extension of the AddNDistributedCache() method of ASP.Net Core.
public void ConfigureServices(IServiceCollection services)
{
services.AddNCacheDistributedCache(configuration =>
{
configuration.CacheName = "IDGDistributedCache";
configuration.EnableLogs = true;
configuration.ExceptionsEnabled = true;
});
services.AddMvc().SetCompatibilityVersion
(CompatibilityVersion.Version_2_2);
}
And that’s all you need to do. You can now start using NCache in your project.
Use NCache to store and retrieve cached objects in ASP.Net Core
The following code snippet illustrates how you can work with NCache. The GetAuthor method shown below retrieves the Author object from the cache if it is available. If the Author object is not available in the cache, the GetAuthor method fetches it from the database and then stores the object in the cache.
public async Task<Author> GetAuthor(int id)
{
_cache = NCache.InitializeCache("CacheName");
var cacheKey = "Key";
Author author = null;
if (_cache != null)
{
author = _cache.Get(cacheKey) as Author;
}
if (author == null) //Data not available in the cache
{
//Write code here to fetch the author
// object from the database
if (author != null)
{
if (_cache != null)
{
_cache.Insert(cacheKey, author, null,
Cache.NoAbsoluteExpiration,
TimeSpan.FromMinutes(10),
Alachisoft.NCache.Runtime.
CacheItemPriority.Default);
}
}
}
return author;
}
And here is the Author class.
public class Author
{
public int AuthorId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
NCache from Alachisoft is a distributed caching solution for .Net. The IDistributedCache interface provides a standard API for working with a distributed cache in ASP.Net Core. You can use it to plug in third-party caches like NCache quickly and easily.