Distributed Caching in ASP.NET Core

Sankhadip Samanta
5 min readJun 24, 2020

--

A distributed cache is a cache shared by multiple app servers, typically maintained as an external service to the app servers that access it. A distributed cache can improve the performance and scalability of an ASP.NET Core app, especially when the app is hosted by a cloud service or a server farm.

For more information about Distributed Caching check Microsoft Documentation

SQL Server

.NET is a free, cross-platform, open-source developer platform for building many different types of applications. With .NET, you can use multiple languages, editors, and libraries to build for web, mobile, desktop, gaming, and IoT.

IDE

I will show you how to implement this project in Visual Studio 2019

Purpose of tutorial

This article will take you though some of the basic concepts of c# like Generic and asp.net core Dependency Injection and most importantly Distributed Caching, a reusable component. Caching is a very useful part of large applications, it minimizes the cost of making DB calls in API request. Here we will be implementing Distributed Caching. Let’s go ahead and get started.

Implementing project using Visual Studio

Creating new project

Search for ASP.NET core web application and select it. Then click on Next

Name the Project DistributedCaching and select all dropdown according to above selection. Then click on Create

Choose API on next screen

Package Installation

Right-click on Project Solution select Manage Nuget Package and Install the following packages

· System.Data.SqlClient

Configuration

After the project creation, go to Startup.cs. In the ConfigureServices method, we need to add Distributed Memory Cache service.

In appsettings.json, we need to write our SQL server data source, user, password, and database that will be used by our project

"ConnectionStrings": {"SqlServerCString": "Data Source=localhost;Initial Catalog=caching;Persist Security Info=True;User ID=sa;Password=1234;"}

A complete view of appsettings.json

Create Database

  • Open your SQL Server Management Studio and create a database named caching.
  • Then open your query window and create a table named Student with the following query and insert some data using the following query

Create Controller

Click on the Controllers folder and add a new Controller. On the next screen select API Controller Empty and Click on Add

On the next screen name the controller CachingController and click on Add

Then open CachingController and do the following

[Route("api/[controller]")]

to

[Route("api/caching")]

Create Database Model

Create a folder and name it Model, add Student.cs with the following code. Make Model serializable for further serializing in setting cache

Place the below code inside CachingController

After placing code, make a request from POSTMAN to https://localhost:<PORT>/api/caching and you will get back the following response. You can notice response time 1348 MS

Create a folder Service and add MemoryCache.cs class and IMemoryCache.cs with the following code.

IMemoryCache.cs

MemoryCache.cs

After placing all code accordingly, we will do Dependency Injection MemoryCache in Startup.cs. Add the following code inside the ConfigureServices method

Now MemoryCache implementation available throughout Application Lifetime and an instance will be created every time there will be a request to the server.

Now let’s go for caching the result after fetching data from Student Table

  • First, let’s receive MemoryCache through Constructor Injection in CachingController.cs with the following code.
  • · Let’s cache student list after fetching data from Student Table, update the GetResult method in CachingController with the following code
It will set cache named student and send back response to Client.

So now fetched data from DB is now stored in a cache, now we have to check if student data available in the cache then fetch data from the cache otherwise make DB call and store it in the cache using the same method. Update the GetResult method with the following code.

Check if it is in cache then extract and send back otherwise make DB hit and set cache, send back to client

So now make a request from POSTMAN to https://localhost:<PORT>/api/caching and see the difference in response time

Too less than before

You can see time 7 MS, this makes a huge difference in server efficiency using the caching method.

Now, we have created a service that will be injected in Startup.cs file, a component that can be used in any project for caching. One more point if you want to remove a particular cache from memory then in the same way call removeCache and pass the CacheKeys inside the function. It will remove cache from memory.

Check out GitHub Repository for Source Code

https://github.com/dev-sankhadip/Distributed-Caching-asp.net-core

Sankhadip Samanta

Full Stack Developer in Various Tech, Code Quotient

Follow me on Linkedin 😃 and Github 😅

--

--

Sankhadip Samanta
Sankhadip Samanta

No responses yet