Introduction
Caching has become a prevalent practice in the software industry due to its ability to enhance application performance and scalability. Caching is a strategy used to enhance the efficiency of data retrieval by storing frequently accessed or utilized data so that data can be served much faster to the client from the Database. These selected datasets are then copied to temporary storage. By doing so, subsequent requests for the same data can be serviced much more quickly. It has been used by many applications such as Amazon, Flipkart, Facebook, etc where responsiveness and a seamless user experience are crucial.
What is Caching?
Caching is a technique used in computing to store and retrieve data more quickly by keeping a copy of frequently accessed or recently used information in a location that allows for faster retrieval. Instead of recalculating or re-fetching the same data from its original source every time it is needed, the system retrieves the cached copy, which is readily available and quicker to access.

Caching helps improve the performance and efficiency of applications and systems by reducing the time it takes to access data. It is commonly used in various contexts, such as web browsers, databases, and application servers. By storing copies of frequently accessed data closer to the point of use, caching reduces the need to perform resource-intensive operations, ultimately leading to faster response times and better overall system performance. ASP.NET Core supports several different caches. The simplest cache is based on the In-Memory Caching.
In-Memory Cache
In-memory caching is a pivotal aspect of optimizing system performance by storing frequently accessed data in the system’s RAM (Random Access Memory). It involves utilizing the server’s memory to store cached data. This caching approach is well-suited for scenarios involving a single server or multiple servers employing session affinity, also referred to as sticky sessions. Session affinity ensures that requests from a specific client consistently reach the same server for processing. It has key benifits like
- Fast Retrieval
- Improved Performance
- Scalability
- Reduced Database Load
Implementation of In-Memory Caching in .Net Core
Step 1: Create a .NET Core Project
Begin by creating a new .NET Core project using your preferred development environment or the command line.
Step 2: Install the Microsoft.Extensions.Caching.Memory Package
In your project, install the Microsoft.Extensions.Caching.Memory NuGet package. This package provides the necessary libraries for in-memory caching.
dotnet add package System.Runtime.Caching
Step 3: Create the Model folder and create one TravelerDetailsClass inside that with details
namespace InMemoryCaching.Model
{
public class TravelerDetails
{
public int TravelerID { get; set; }
public string? Name { get; set; }
public string? Address { get; set; }
public string? ContactNumber { get; set; }
public DateTime DOB { get; set; }
public DateTime DateOfVisit { get; set; }
public string? Email { get; set; }
}
}
Step 4: Create a Generic Interface & Service to setup caching methods
namespace InMemoryCaching.Interface
{
public interface ICacheService
{
T GetData<T>(string key);
bool SetData<T>(string key, T value, DateTimeOffset expirationTime);
object RemoveData(string key);
}
}
using InMemoryCaching.Interface;
using System.Runtime.Caching;
namespace InMemoryCaching.Services
{
public class CacheService: ICacheService
{
ObjectCache _memoryCache = MemoryCache.Default;
public T GetData<T>(string key)
{
try
{
T item = (T)_memoryCache.Get(key);
return item;
}
catch (Exception)
{
throw;
}
}
public bool SetData<T>(string key, T value, DateTimeOffset expirationTime)
{
bool res = true;
try
{
if (!string.IsNullOrEmpty(key))
{
_memoryCache.Set(key, value, expirationTime);
}
}
catch (Exception)
{
throw;
}
return res;
}
public object RemoveData(string key)
{
try
{
if (!string.IsNullOrEmpty(key))
{
return _memoryCache.Remove(key);
}
}
catch (Exception)
{
throw;
}
return false;
}
}
}
Step 5: Add DbContext class for Database Connection
using InMemoryCaching.Model;
using Microsoft.EntityFrameworkCore;
namespace InMemoryCaching.DbContext
{
public class DbContextClass : Microsoft.EntityFrameworkCore.DbContext
{
public DbContextClass(DbContextOptions<DbContextClass> options) : base(options) { }
public DbSet<TravelerDetails> TravelerDetails { get; set;}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TravelerDetails>().HasKey(t => t.TravelerID);
}
}
}
Step 6: Now we will utilize cache service in our controller & Entity setup
using InMemoryCaching.Interface;
using InMemoryCaching.Model;
using Microsoft.AspNetCore.Mvc;
namespace InMemoryCaching.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class TravelController : ControllerBase
{
private readonly ICacheService _cacheService;
private readonly ITravelService _travelService;
public TravelController(ICacheService cacheService, ITravelService travelService)
{
_cacheService = cacheService;
_travelService = travelService;
}
[HttpGet("GetTravelerDetails")]
public async Task <IEnumerable<TravelerDetails>> GetTravelerDetails()
{
var cacheData = _cacheService.GetData<IEnumerable<TravelerDetails>>("TravelerDetails");
if (cacheData != null)
{
return cacheData;
}
var expirationTime = DateTimeOffset.Now.AddMinutes(5.0);
cacheData = await _travelService.GetTravelerDetails();
_cacheService.SetData<IEnumerable<TravelerDetails>>("TravelerDetails", cacheData, expirationTime);
return cacheData;
}
}
}
using InMemoryCaching.DbContext;
using InMemoryCaching.Interface;
using InMemoryCaching.Model;
using Microsoft.EntityFrameworkCore;
namespace InMemoryCaching.Services
{
public class TravelService : ITravelService
{
private readonly DbContextClass _dbContext;
public TravelService(DbContextClass dbContext)
{
_dbContext = dbContext;
}
public async Task<IEnumerable<TravelerDetails>> GetTravelerDetails()
{
return await _dbContext.TravelerDetails.ToListAsync();
}
}
}
using InMemoryCaching.Model;
namespace InMemoryCaching.Interface
{
public interface ITravelService
{
Task <IEnumerable<TravelerDetails>> GetTravelerDetails();
}
}
Step 7: Injecting Dependencies in Startup.cs
// Add services to the container.
builder.Services.AddDbContext<DbContextClass>(opt =>
opt.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddControllers();
builder.Services.AddScoped<ICacheService, CacheService>();
builder.Services.AddScoped<ITravelService, TravelService>();
Conclusion
In-memory caching is a powerful technique for optimizing performance in .NET Core applications. By following this step-by-step guide, you can seamlessly implement in-memory caching and unlock the benefits of improved response times, reduced database load, and enhanced scalability in your projects. Experiment with different caching strategies, and monitor your application’s performance to fine-tune the caching mechanism for optimal results. Happy coding!