How to use NCache in ASP.NET Core

By FoxLearn 1/7/2025 7:44:01 AM   15
Although ASP.Net Core doesn't include a cache object, it supports various caching methods, such as in-memory caching, distributed caching, and response caching.

NCache, an open-source solution from Alachisoft, is a high-speed, in-memory, distributed, and scalable caching framework built specifically for .Net applications.

A distributed cache like NCache enhances application performance and scalability by storing cached data across multiple servers rather than a single web server's memory. This allows for seamless server additions or removals without affecting the cache, and ensures data remains accessible even if some servers fail or become unresponsive.

To get started with NCache in your new ASP.Net Core project, install the NuGet package Alachisoft.NCache.SessionServices using the NuGet Package Manager or console.

Using the IDistributedCache interface in ASP.NET Core

To implement a distributed cache in ASP.Net Core applications, you should use the IDistributedCache interface, which was introduced to facilitate integration with third-party caching frameworks.

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 enable distributed caching with NCache, call the AddNCacheDistributedCache method within the ConfigureServices method in your Startup.cs file, as shown in the following code snippet.

public void ConfigureServices(IServiceCollection services)
{
    services.AddNCacheDistributedCache(configuration =>
    {
        configuration.CacheName = "IDGDistributedCache";
        configuration.EnableLogs = true;
        configuration.ExceptionsEnabled = true;
    });
}

The AddNCacheDistributedCache() method is an extension of ASP.Net Core's AddDistributedCache() method.

Using NCache to store and retrieve cached objects in ASP.NET Core

For example, how to interact with NCache.

public async Task<Book> GetBook(int id)
{
    _cache = NCache.InitializeCache("MyCache");
    var cacheKey = "Book_" + id;
    Book book = null;

    if (_cache != null)
    {
        book = _cache.Get(cacheKey) as Book;
    }

    if (book == null) // Data not available in the cache
    {
        // Code to fetch the book object from the database
        if (book != null)
        {
            if (_cache != null)
            {
                _cache.Insert(cacheKey, book, null,
                    Cache.NoAbsoluteExpiration,
                    TimeSpan.FromMinutes(15),
                    Alachisoft.NCache.Runtime.CacheItemPriority.Default);
            }
        }
    }

    return book;
}

The GetBook method retrieves the Book object from the cache if available. If it's not found in the cache, the method fetches the Book object from the database and then stores it in the cache.

Here is the Book class:

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public string Author { get; set; }
}

NCache, a distributed caching solution from Alachisoft, integrates with ASP.Net Core via the IDistributedCache interface. This interface provides a standard API for working with distributed caches, allowing easy integration with third-party caching systems like NCache.