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.
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?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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With