Sunday, February 9, 2025

How to Implement In Memory Caching in .net

 

Introduction

In modern web applications, performance is key. Fetching data repeatedly from a database can lead to increased response times and higher server load. One effective way to optimize performance is by using in-memory caching to store frequently accessed data. In this blog, we will explore how to integrate IMemoryCache in an ASP.NET Core Web API project to efficiently handle CRUD operations for a Student entity.

What is In-Memory Caching?

In-memory caching is a mechanism that temporarily stores frequently accessed data in memory, reducing the need to retrieve it from the database each time. ASP.NET Core provides IMemoryCache, which is a simple, high-performance, and thread-safe cache.

Setting Up the Project

To demonstrate in-memory caching, let’s build an ASP.NET Core Web API with a StudentController that performs CRUD operations using Entity Framework Core.

1. Install Required Dependencies

Ensure you have the necessary NuGet packages installed in your ASP.NET Core project:




2. Add Model and  AppDb Context file



Student Model

AppDb Context File

3. Add in Appsettings.json just below of AllowedHosts by put comma

Connection String

4. Add Settings

Program.cs

5. Add-Migration and Update-database run two commands
6. add Controller with name Student

Student Controller

6. SetSlidingExpiration: refreseh if no activity in 10 min
SetAbsoluteExpiration : always refresh after 1 hour

Expalin memory Cache options

Note: In this i used semaphoreslim for single process optimised the in memory cache. I am updating the in memory cache when add and update and delete. also this approch is helpfull for single server or small level applications. for multiserver or high level application we should go with distributed cache technique like redis so our ram not effected to much.

Clone this poc:InMemoryCachePOC

No comments:

Post a Comment

How to Do Cross-Browser Testing on Windows — Including Safari via Playwright

To test follow few steps: Step 1. Install node Step 2. create Folder and run these commands commands Copy Code ...