I solved it by creating a FlushableMemoryCache
singleton around IMemoryCache
, which tracks the keys currently stored in the cache and then can just iterate over them to flush them all:
public interface IFlushableMemoryCache
{
void Set<T>(string cacheId, object key, T value);
bool TryGetValue<T>(object key, out T value);
void Remove(string cacheId, object key);
void Flush(string cacheId);
}
public class FlushableMemoryCache : IFlushableMemoryCache
{
private readonly IMemoryCache _memoryCache;
private readonly ConcurrentDictionary<string, HashSet<object>> _keyDictionary;
public FlushableMemoryCache(IMemoryCache memoryCache)
{
_memoryCache = memoryCache;
_keyDictionary = new ConcurrentDictionary<string, HashSet<object>>();
}
public void Set<T>(string cacheId, object key, T value)
{
_memoryCache.Set(key, value);
_keyDictionary.AddOrUpdate(cacheId, new HashSet<object>(new[] {key}),
(id, oldVal) =>
{
oldVal.Add(key);
return oldVal;
});
}
public bool TryGetValue<T>(object key, out T value)
{
return _memoryCache.TryGetValue(key, out value);
}
public void Remove(string cacheId, object key)
{
_memoryCache.Remove(key);
if (_keyDictionary.ContainsKey(cacheId) && _keyDictionary[cacheId].Contains(key))
{
_keyDictionary[cacheId].Remove(key);
}
}
public void Flush(string cacheId)
{
foreach (var key in _keyDictionary[cacheId])
{
_memoryCache.Remove(key);
}
_keyDictionary[cacheId] = new HashSet<object>();
}
}
The services which make use of this will need to provide a cacheId
which is unique to that service. That allows the Flush
to only clear keys related to the specific service, and not everything in the cache!
ObjectDisposedException: Cannot access a disposed object. Object name: 'Microsoft.Extensions.Caching.Memory.MemoryCache'.