0

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?

Mark Erasmus
  • 2,305
  • 6
  • 25
  • 37
  • Do they run in the same appdomain? http://stackoverflow.com/questions/5986051/c-sharp-static-variables-scope-and-persistence – CodeCaster Aug 07 '14 at 20:37

1 Answers1

1

So far I understand, the service layer is a WCF project. If this is true, it runs on a separated application domain than MVC web site. The cache you're using stores things on the application domain memory, it won't be shared across different ones.

Claudio Redi
  • 67,454
  • 15
  • 130
  • 155