I am using the System.Runtime.Caching
library to implement caching in an ASP.NET MVC application that utilises a service layer (WCF) but I am getting some strange behaviour. Here is my cache helper class:
public class CacheHelper
{
private static readonly ObjectCache _cache = MemoryCache.Default;
public static T Get<T>(string key) where T : class
{
try
{
return (T) _cache[key];
}
catch (Exception)
{
return null;
}
}
public static void Add<T>(string key, T objectToCache) where T : class
{
_cache.Add(key, objectToCache, DateTime.Now.AddMinutes(5));
}
public static void Add(string key, object objectToCache)
{
_cache.Add(key, objectToCache, DateTime.Now.AddMinutes(5));
}
public static void Clear(string key)
{
_cache.Remove(key);
}
public static void ClearAll()
{
List<string> keys = _cache.Select(c => c.Key).ToList();
foreach (var key in keys)
{
_cache.Remove(key);
}
}
/// omitted for brevity
}
If I add a result to the cache from my service layer the item is successfully added to cache and the _cache.GetCount()
returns 1. If I try CacheHelper.ClearAll()
from the service layer it's all good. However, if I tried and call CacheHelper.ClearAll()
from a controller the cache appears empty and _cache.GetCount()
is 0, and I can't work out why?