How Do I Use InMemoryCache in .Net Core

Barkın Kızılkaya
Geek Culture
Published in
2 min readJul 22, 2022

In This Article, we will focus on caching

We can start with a simple question! Why do we need a cache?

Because applications work with data and is generally data comes from outside of the application. With cache this can be perform very quick way.

There are two types of caching in this article we will focus on In-Memory Caching.This caching data is stored in application server memory. Actually, we can say it is inside of the ram.

Let’s start to write some code.

In this sample I used .Net Core 6 and Mvc application. After creation we can create new controller It can named MemoryController. After that we need to add memory cache service to the program file

builder.Services.AddMemoryCache();

Now we can use memory cache service via dependency injection.

private readonly IMemoryCache _memoryCache;public MemoryController(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
}

With the help of get set methods we can write and read cache.

public IActionResult Index()
{
_memoryCache.Set<string>("Time", DateTime.Now.ToLongTimeString());
return View();
}
public IActionResult Show()
{
ViewBag.Time = _memoryCache.Get<string>("Time");
return View();
}

when you run memory controller it will set cache with set function then with show page you will going to see cached time.

var value = _memoryCache.GetOrCreate("Time", entry =>
{
return DateTime.Now.ToLongTimeString();
});
return View();

GetOrCreate can use for get or set. İf we use this instead of get and set method. we don’t need to check our key exist in data or not.

AbsoluteExpiration : This is a time which our data will stay in cache. For example if we set 5 min. It will stay in memory 5 min. than it will remove.
SlidingExpiration: this also our cache time but the difference is. for example we have data in cache we set 5 min. If somebody reach data in 5 min it will refresh time. And will start 5 min timer again. İf not then it will remove

var value = _memoryCache.GetOrCreate("Time", entry =>
{
entry.AbsoluteExpiration = DateTime.Now.AddSeconds(100);
entry.SlidingExpiration = TimeSpan.FromSeconds(20);
return DateTime.Now.ToLongTimeString();
});

Priority : Memory has limits. Because of that, with the usage of memory data will fill ram. With priority we can set which daha will remove first.

entry.Priority = CacheItemPriority.NeverRemove;

RegisterPostEvictionCallback : runs when if something happen to our cached data. When we cache reasons then we can learn why our data is deleted. is it expire or lack of memory.

entry.RegisterPostEvictionCallback((key, value, reason, state) =>
{
_memoryCache.Set("CallBack", $"{key}--> {value} : reason:{reason}");
});

Cache is important for application. we can cache various types. But don’t forget In memory cache uses ram. if we put unnecessary object to the rem it will fill memory. And this can have some side effect.

This article was first part of the caching. In second part I will try to explain redis cache

--

--