skip to Main Content

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?

2

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.

    Login or Signup to reply.
  1. You need to add memory cache service into Program.cs
    If i give you some suggestion about it, you should create a wrapper to use memory cache. However you cannot add unit tests. Because most of func are static.
    For second question you can use MemoryCacheEntryOptions class. There are so many option for cache. If you would like to store too long time you can set .SetAbsoluteExpiration(DateTimeOffset.MaxValue) like that

     var options= new MemoryCacheEntryOptions()
                            .SetSlidingExpiration(TimeSpan.FromSeconds(60))
                            .SetAbsoluteExpiration(DateTimeOffset.MaxValue)
                            .SetPriority(CacheItemPriority.High);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search