Cache in ASP.NET Core

ASP.NET Core 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();

here’s how you can use it

public service(IMemoryCache cache, AppDbContext context)
{
	public Person GetPerson(string id)
	{
		if(!cache.TryGetValue(id, out Person person))
		{
			person = context.Persons.Find(id);

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

			cache.Set(id, person, cacheEntryOptions);
		}

		return person;
	}
}

Reference(s)

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