In one of the applications I’m building I wanted to abstract away the usage of the .NET MemoryCache behind a nice clean interface:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Implement this interface as an abstraction of a Cache implementation | |
/// </summary> | |
public interface ICache<K, V> | |
{ | |
/// <summary> | |
/// Get the object from the Cache | |
/// </summary> | |
/// <param name="key"></param> | |
/// <returns></returns> | |
V Get(K key); | |
/// <summary> | |
/// Put the object in the cache | |
/// </summary> | |
/// <param name="key"></param> | |
/// <param name="value"></param> | |
void Put(K key, V value); | |
/// <summary> | |
/// Remove an item from the Cache. | |
/// </summary> | |
/// <param name="key">The Key of the Item in the Cache to remove.</param> | |
void Remove(K key); | |
/// <summary> | |
/// Clear the Cache | |
/// </summary> | |
void Clear(); | |
} |
Implementing most parts of this interface wasn’t hard but I struggled with the Clear method. There is no easy way to just clear all items from the MemoryCache. I tried the Trim() method but it had not the desired effect. I was able to solve it by disposing the existing cache instance and creating a new one behind the scenes. Here is the complete implementation:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class InMemoryCache:ICache<string,object> | |
{ | |
private MemoryCache _cache; | |
public InMemoryCache(string name="SampleCache") | |
{ | |
_cache = new MemoryCache(name); | |
} | |
public object Get(string key) | |
{ | |
return _cache[key]; | |
} | |
public void Put(string key, object value) | |
{ | |
_cache[key] = value; | |
} | |
public void Remove(string key) | |
{ | |
_cache.Remove(key); | |
} | |
public void Clear() | |
{ | |
var oldCache = _cache; | |
_cache = new MemoryCache("SampleCache"); | |
oldCache.Dispose(); | |
} | |
} |