Joydip Kanjilal
Contributor

How to use NCache in ASP.Net Core

how-to
Feb 25, 20194 mins
C#Development ToolsMicrosoft .NET

Take advantage of Alachisoft’s free, open-source, distributed, in-memory cache to improve the performance and scalability of your ASP.Net Core applications

hyper convergence speed burning rubber tire binary fast by tao55 getty images
Credit: Toa55 / Getty Images

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.

A distributed cache such as NCache can improve both the performance and scalability of applications. In a distributed cache, the cached data doesn’t reside in the memory of an individual web server. You can add or remove a server without impacting the cache or the cached data. And if any of the servers go down or stop responding, other servers will still be able to retrieve the cached data. This explains why the cached data in a distributed cache can survive server restarts.

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.

  1. Launch the Visual Studio 2017 IDE.
  2. Click on File > New > Project.
  3. Select “ASP.Net Core Web Application (.Net Core)” from the list of the templates displayed.
  4. Specify a name for the project.
  5. Click OK to save the project.
  6. A new window “New .Net Core Web Application…” is shown next.
  7. Select .Net Core as the runtime and ASP.Net Core 2.2 (or later) from the drop-down list at the top.
  8. Select API as the project template
  9. Ensure that the check boxes “Enable Docker Support” and “Configure for HTTPS” are unchecked as we won’t be using those features here.
  10. Ensure that “No Authentication” is selected as we won’t be using authentication either.
  11. 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author