On first look this looks duplicate of this question, but I am not asking how to clear cache for EF.
How can I clear entire cache set by IMemoryCache
interface?
public CacheService(IMemoryCache memoryCache)
{
this._memoryCache = memoryCache;
}
public async Task<List<string>> GetCacheItem()
{
if (!this._memoryCache.TryGetValue("Something", out List<string> list))
{
list= await this ...
this._memoryCache.Set("Something", list, new MemoryCacheEntryOptions().SetPriority(CacheItemPriority.NeverRemove));
}
return list;
}
This is just an example. I have many classes/methods that are storing values to cache. Now I need to remove them all.
My keys are, in some cases, created dynamically, so I don't know which keys I need to remove. Clear would be perfect.
I could write my own interface and class which would internally use IMemoryCache
, but this seems overkill. Is there any easier options?
This is not possible. I looked up the code on github because my initial idea was to simply dispose it, even when it would be dirty. Caching-Middleware registers a single implementation of IMemoryCache as singleton.
When you called dispose on it once, you can not access the cache functions ever again, until you restart the whole service.
So a workaround to accomplish this would be to store all keys that have been added in singleton service that you implement yourself. For instance smth like
With that you could at somepoint access all keys, iterate through them and call the Remove(object key) function on the cache.
Dirty workaround, might cause some trouble but as far as I can tell this is the only way to remove all items at once without a service reboot :)
Because I couldn't found any good solution I write my own.
In SamiAl90 solution (answer) I missed all properties from ICacheEntry interface.
Internally it uses IMemoryCache.
Use case is exactly the same with 2 additional features:
You have to register singleton:
Use case:
Source: