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.
- 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? - What is the lifetime of the data stored in the cache?
2
Answers
As was pointed out above it is volatile and will not survive an application reset
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