ASP.NET Core MVC Interview Question #143
What is in-memory caching and when should it be used?
Dependency Injection, Services, Error Handling, Logging & Performance Senior Advanced
Quick Interview Answer
IMemoryCache stores data in the memory of the current application process. It is useful for relatively small, frequently reused data that can be recreated and does not need to be shared across multiple server instances.
Detailed Explanation
IMemoryCache stores data in the memory of the current application process. It is useful for relatively small, frequently reused data that can be recreated and does not need to be shared across multiple server instances.
Because each application instance has its own memory cache, it is not automatically consistent across a server farm. Cache entries also disappear when the process restarts.
Code Example
public Product? GetCached(int id)
{
return _cache.GetOrCreate(
$"product:{id}",
entry =>
{
entry.AbsoluteExpirationRelativeToNow =
TimeSpan.FromMinutes(5);
return LoadProduct(id);
});
}