Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it necessary to call services.AddMemoryCache()?

I am writing some middleware that would benefit from a memory cache. So I'm using dependency injection to provide an IMemoryCache instance.

public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager, IMemoryCache cache)
{
    // Access cache here...
}

This seems to be working, but I have a few questions.

  1. The instructions I found said to call services.AddMemoryCache() in my initialization. But it works fine if I don't. Can someone tell me what this method does and when I need to call it?
  2. What is the lifetime of the data stored in the cache?
like image 528
Jonathan Wood Avatar asked Sep 18 '25 11:09

Jonathan Wood


1 Answers

  1. It will register it in your DI so that it can be used. Failure to set it in the DI container will make it an unresolved service. See a working fiddle here;
  2. The lifetime will be until it is cleared. It can be cleared by command or by setting the lifetime for the cached item. This can be done globally or individually like in the example below.
package Microsoft.Extensions.DependencyInjection
package Microsoft.Extensions.Caching.Memory
package Microsoft.Extensions.Caching.Abstractions
// program.cs

// add it without options 
builder.Services.AddMemoryCache();

// set global expiry for memory
builder.Services.AddMemoryCache(opts => new MemoryCacheEntryOptions()
    .SetSlidingExpiration(TimeSpan.FromDays(1))
    .SetAbsoluteExpiration(TimeSpan.FromDays(7))
);

// in your task (only set the absolute)
cache.Set("key", "value", TimeSpan.FromDays(1));

As was pointed out above it is volatile and will not survive an application reset

There are 2 hard problems in computer science:
cache invalidation, naming things, and off-by-1 errors.

like image 146
Kieran Avatar answered Sep 21 '25 02:09

Kieran