Caching in .NET (`IMemoryCache`)

.NET offers several cache types. I’m going to explore here IMemoryCache which stores data in the memory of the web server. It’s simple but not suitable for distributed scenarios.

first of all we need to register the services

builder.Services.AddMemoryCache();

GetOrCreateAsync

here’s how you can inject and use it, without manipulating the cache itself

public class PersonService(IMemoryCache _cache)
{
	private const string CACHE_PERSON_KEY = "PersonService:GetPerson:";

	public async Task<Person> GetPerson(string id)
	{
		return await _cache.GetOrCreateAsync(CACHE_PERSON_KEY + id, async entry =>
		{
			entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(5);
			return await GetPersonNoCache(id);
		});
	}

	public async Task<Person> GetPersonNoCache(string id)
	{
		// do operations to get a person here
	}
}

TryGetValue

this is a more manual approach.

public class PersonService(AppDbContext _context, IMemoryCache _cache)
{
	private const string CACHE_PERSON_KEY = "PersonService:GetPerson:";

	public async Task<Person> GetPerson(string id)
	{
		if(!_cache.TryGetValue(CACHE_PERSON_KEY+id, out Person person))
		{
			person = await context.Persons.Find(id);

			var cacheEntryOptions = new MemoryCacheEntryOptions()
				.SetAbsoluteExpiration(TimeSpan.FromMinutes(10))
				.SetSlidingExpiration(TimeSpan.FromMinutes(2));

			cache.Set(CACHE_PERSON_KEY+id, person, cacheEntryOptions);
		}
		return person;
	}
}

Reference(s)

https://www.milanjovanovic.tech/blog/caching-in-aspnetcore-improving-application-performance