Take advantage of a distributed cache to improve the performance and scalability of your ASP.Net Core application Credit: Thinkstock ASP.Net Core provides support for various types of caching. In addition to in-memory caching and response caching, it provides built-in support for distributed caching. In one of my previous articles here, I discussed in-memory caching in ASP.Net Core. In this article we will examine how we can work with distributed caching in ASP.Net Core. We will discuss both supported implementations, i.e., using Redis as well as SQL Server as the cache stores. What is a distributed cache Distributed caches are used to improve the performance and scalability of applications. Typically, a distributed cache is shared by multiple application servers. In a distributed cache, the cached data doesn’t reside in the memory of an individual web server. Rather, this data is stored centrally so that it is available to all of the application’s servers. If any of the servers go down or stop responding, other servers will still be able to retrieve the cached data. Another advantage of a distributed cache is that the cached data survives server restarts. You can add or remove a server without impacting the cache or the cached data. To take advantage of a distributed cache when working on ASP.NET Core applications, we will use the IDistributedCache interface. We’ll examine how the IDistributedCache interface differs from the IMemoryCache interface in the section that follows. The IDistributedCache interface The IDistributedCache interface used for distributed caching in .NET Core is more complex than the IMemoryCache interface used to cache data in the memory of an individual web server. Here is a look at the simpler IMemoryCache interface. public interface IMemoryCache : IDisposable { bool TryGetValue(object key, out object value); ICacheEntry CreateEntry(object key); void Remove(object key); } The IDistributedCache interface is designed for a web farm scenario. The IDistributedCache interface comprises a collection of synchronous and synchronous methods that enable you to add, retrieve, or remove items from a centralized cache. Here is a look at the IDistributedCache interface. public interface IDistributedCache { byte[] Get(string key); Task<byte[]> GetAsync(string key); void Set(string key, byte[] value, DistributedCacheEntryOptions options); Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options); void Refresh(string key); Task RefreshAsync(string key); void Remove(string key); Task RemoveAsync(string key); } Note that while IDistributedCache works with byte[], the framework provides necessary extension methods so that you can work with string objects as well. You can even write your own extension methods to work with custom data types if need be. To use the IDistributedCache interface in an ASP.NET Core application, follow these steps: In the Visual Studio IDE, click on File > New > Project. Select “ASP.Net Core Web Application (.Net Core)” from the list of templates displayed. Specify a name for the project. Click OK to save the project. In the “New .Net Core Web Application…” window, select “Web API.” Ensure that “Enable Docker Support” is unchecked and that “No Authentication” is selected as we won’t be using either of these here. Click OK. Select the project you just created in the Solution Explorer window. Next, add the “Microsoft.Extensions.Caching.Abstractions” NuGet package to your project. As of this writing, the latest stable version of this package is 2.0.0. How to implement a distributed cache in .Net Core using Redis First off, you should install the Redis package via the NuGet Package Manager console or NuGet Package Manager Window. Install-Package Microsoft.Extensions.Caching.Redis To enable Redis as a distributed cache store for your application, you need to take advantage of the AddDistributedCache method. Here is the syntax for configuring a distributed cache using Redis in .Net Core. services.AddDistributedRedisCache (option => { option.Configuration ="Specify the connection string"; option.InstanceName ="Specify the instance name"; }); Now add the following piece of code to the ConfigureService method in the Startup.cs file. public void ConfigureServices(IServiceCollection services) { services.AddMvc(); services.AddDistributedRedisCache(option => { option.Configuration ="localhost"; option.InstanceName ="IDG"; }); } How to use the IDistributedCache interface in controller methods The following code listing illustrates how you can use IDistributedCache to insert or retrieve data from a Redis cache in your controller methods. public class DefaultController : Controller { private readonly IDistributedCache _distributedCache; public HomeController(IDistributedCache distributedCache) { _distributedCache = distributedCache; } [HttpGet] public async Task<string> Get() { var cacheKey ="IDG"; var data = _distributedCache.GetString(cacheKey); if (!string.IsNullOrEmpty(data)) { return data; //returned from Cache } else { string str ="Hello World"; _distributedCache.SetString(cacheKey, str); return str; } } } How to implement a distributed cache in .Net Core using SQL Server While the Redis implementation of IDistributedCache is available in the Microsoft.Extensions.Caching.Redis NuGet package, the SQL Server implementation is available as part of the Microsoft.Extensions.Caching.SqlServer NuGet package. So, to leverage SQL Server as the distributed cache repository, enter the following command in the NuGet Package Manager console. Install-Package Microsoft.Extensions.Caching.SqlServer To use SQL Server as the distributed cache, specify the following code in the ConfigureServices method. services.AddDistributedSqlServerCache(x => { x.ConnectionString = Configuration["ConnectionStrings:Default"]; x.SchemaName ="dbo"; x.TableName ="IDGCache"; }); You should install the following NuGet package (CLI tool) for creating the necessary database tables to store the cached data. Microsoft.Extensions.Caching.SqlConfig.Tools Next you should run the following command to create the database tables for your cache store. dotnet sql-cache create <connection string> <schema> <table class="legacyTable"> ASP.Net Core provides an abstraction over distributed caching. As a result, regardless whether the underlying cache store in use is Redis or SQL Server, the IDistributedCache interface provides a uniform and easy-to-use API for storing and retrieving data from a distributed cache. The IDistributedCache interface can also be injected to your controllers easily using dependency injection. Related content feature What is Rust? Safe, fast, and easy software development Unlike most programming languages, Rust doesn't make you choose between speed, safety, and ease of use. Find out how Rust delivers better code with fewer compromises, and a few downsides to consider before learning Rust. By Serdar Yegulalp Nov 20, 2024 11 mins Rust Programming Languages Software Development how-to Kotlin for Java developers: Classes and coroutines Kotlin was designed to bring more flexibility and flow to programming in the JVM. Here's an in-depth look at how Kotlin makes working with classes and objects easier and introduces coroutines to modernize concurrency. By Matthew Tyson Nov 20, 2024 9 mins Java Kotlin Programming Languages analysis Azure AI Foundry tools for changes in AI applications Microsoft’s launch of Azure AI Foundry at Ignite 2024 signals a welcome shift from chatbots to agents and to using AI for business process automation. By Simon Bisson Nov 20, 2024 7 mins Microsoft Azure Generative AI Development Tools news Microsoft unveils imaging APIs for Windows Copilot Runtime Generative AI-backed APIs will allow developers to build image super resolution, image segmentation, object erase, and OCR capabilities into Windows applications. By Paul Krill Nov 19, 2024 2 mins Generative AI APIs Development Libraries and Frameworks Resources Videos