I want to have a caching class to cache different types. I want each type to be cached in a different MemoryCache
but in a generic way.
Am I doing it right?
internal static class RecordsCache
{
private static Dictionary<string, ObjectCache> cacheStore;
static private CacheItemPolicy policy = null;
static RecordsCache()
{
cacheStore = new Dictionary<string, ObjectCache>();
ObjectCache activitiesCache = new MemoryCache(typeof(Activity).ToString());
ObjectCache lettersCache = new MemoryCache(typeof(Letter).ToString());
ObjectCache contactssCache = new MemoryCache(typeof(Contact).ToString());
cacheStore.Add(typeof(Activity).ToString(), activitiesCache);
cacheStore.Add(typeof(Letter).ToString(), lettersCache );
cacheStore.Add(typeof(Contact).ToString(), contactssCache );
policy = new CacheItemPolicy();
policy.Priority = CacheItemPriority.Default;
policy.AbsoluteExpiration = DateTimeOffset.Now.AddHours(12);
}
public static void Set<T>(string userID, int year, List<T> records)
{
var cache = cacheStore[typeof(T).ToString()];
string key = userID + "-" + year.ToString();
cache.Set(key, records, policy);
}
public static bool TryGet<T>(string userID, int year, out List<T> records)
{
var cache = cacheStore[typeof(T).ToString()];
string key = userID + "-" + year.ToString();
records = cache[key] as List<T>;
return records != null;
}
public static void Remove<T>(string userID, int year)
{
var cache = cacheStore[typeof(T).ToString()];
string key = userID + "-" + year.ToString();
cache.Remove(key);
}
}