In-memory caching in Asp.Net Core

Firat
4 min readDec 13, 2022

--

As you know we use cache to improve performance as well as reduce the DB connections. You can use either the in-memory cache or distributed cache.

However, if you work on a project based on monolithic architecture, you should use in-memory caching.

In-memory caching is so easy to use and also it is effective in terms of your application performance.

Let’s get started and create a web application. Go to the visual studio (I use visual studio) and create a Web API app application.

Select ASP.NET Core Web API and click on the Next button

Fill in the details and click on the Next button

Keep it as it is and hit the Create button

After you create a project, you need to install Microsoft.Extensions.Caching.Memory package which is why right-click on your solution and select Manage NuGet Packages

Search for Microsoft.Extension.Caching.Memory and hit the Install button.

After you install the package, go to the program.cs and add the AddMemoryCache()

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddMemoryCache();

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

Go to the controller and update the controller to have the caching mechanism.

Inject IMemoryCache in the controller.

private readonly IMemoryCache _cache; 

public InMemoryTestController(IMemoryCache cache)
{
this._cache = cache;
}

Create a HttpGet Method and implement a cache in it.

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace InMemoryCaching.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InMemoryTestController : ControllerBase
{
private readonly IMemoryCache _cache;

public InMemoryTestController(IMemoryCache cache)
{
this._cache = cache;
}

[HttpGet]
public IActionResult InMemoryCache()
{
string result = "";
var cacheResult = _cache.Get<string>("CacheKey") ?? "";
if (cacheResult=="")
{
result = FakeDbConnection();
// you can put everything as a cachekey.
// you can configure cache time up to your requirements.
_cache.Set<string>("CacheKey", result, TimeSpan.FromMinutes(2));
}
return Ok(result);
}


private string FakeDbConnection()
{
return "Connected Db";
}

}
}

When you try it the first time, you will see method will call the FakeDbConnection method because the cache is empty. However, if you check it the second time, you will see that cache will return the value and the code will go to return Ok(result) directly.

Besides, TryGetValueto is used to check to see if the value is present in the cache or not. If it is present, the method will return the value otherwise, it will connect to the FakeDbConnection method.

 if (!_cache.TryGetValue("CacheKey",out result))
{
result = FakeDbConnection();
_cache.Set<string>("CacheKey", result, TimeSpan.FromMinutes(2));
}
return Ok(result);

InMemoryTestController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace InMemoryCaching.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InMemoryTestController : ControllerBase
{
private readonly IMemoryCache _cache;

public InMemoryTestController(IMemoryCache cache)
{
this._cache = cache;
}

[HttpGet]
public IActionResult InMemoryCache()
{
string result = "";
//var cacheResult = _cache.Get<string>("CacheKey") ?? "";
//if (cacheResult=="")
//{
// result = FakeDbConnection();
// // you can put everything as a cachekey.
// // you can configure cache time up to your requirements.
// _cache.Set<string>("CacheKey", result, TimeSpan.FromMinutes(2));
//}

if (!_cache.TryGetValue("CacheKey",out result))
{
result = FakeDbConnection();
_cache.Set<string>("CacheKey", result, TimeSpan.FromMinutes(2));
}
return Ok(result);
}


private string FakeDbConnection()
{
return "Connected Db";
}

}
}

This is how caching mechanism works and improves the performance.

You can define cache entry options before you set the cache value if you want to.

InMemoryTestController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;

namespace InMemoryCaching.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class InMemoryTestController : ControllerBase
{
private readonly IMemoryCache _cache;

public InMemoryTestController(IMemoryCache cache)
{
this._cache = cache;
}

[HttpGet]
public IActionResult InMemoryCache()
{
string result = "";
//var cacheResult = _cache.Get<string>("CacheKey") ?? "";
//if (cacheResult=="")
//{
// result = FakeDbConnection();
// // you can put everything as a cachekey.
// // you can configure cache time up to your requirements.
// _cache.Set<string>("CacheKey", result, TimeSpan.FromMinutes(2));
//}

//if (!_cache.TryGetValue("CacheKey", out result))
//{
// result = FakeDbConnection();
// _cache.Set<string>("CacheKey", result, TimeSpan.FromMinutes(2));
//}

if (!_cache.TryGetValue("CacheKey", out result))
{
result = FakeDbConnection();
var cacheOptions = new MemoryCacheEntryOptions()
.SetSlidingExpiration(TimeSpan.FromHours(1))//how long it will be inactive
.SetAbsoluteExpiration(TimeSpan.FromMinutes(10))// if there is a problem with sliding expiration, the absolute expiration will determine the cache
.SetPriority(CacheItemPriority.High)// how important the cache is
.SetSize(2048);//size of cache entry value
_cache.Set<string>("CacheKey", result, cacheOptions);
}


return Ok(result);
}

private string FakeDbConnection()
{
return "Connected Db";
}

}
}

Basically, you have to send the key and get the value once you want to use the cache. Do not forget that you can store variables, models, and so on not only string values.

Note that distributed cache works with the same logic only you need to install docker on your machine and create a container for caching mechanism. We will investigate the distributed caching mechanism in another article.

API: https://github.com/frttnk/In-memory-caching-in-Asp.Net-Core-6

--

--

Firat

I am a Senior Full-Stack .Net Developer who is trying to share hands-on experience and other technologies that are related to Full-stack development.