Search code examples
c#asp.net-mvciismemorycache

Using memorycache in asp.net mvc application it gets created everytime


Environment:
      asp.net mvc
      iis

I have create a wrapper and concrete class around memorycache which in its constrcutor i set memoryCache

  public class AbijMemoryCache : IAbijMemoryCache
{
    private readonly MemoryCache _cache;

    public AbijMemoryCache()
    {
        if (_cache == null)
        {

            _cache = MemoryCache.Default;

        }
    }
}

then in unity for getting only one instance of memory cache I have used ContainerControlledLifetimeManager

  container.RegisterType<IAbijMemoryCache, AbijMemoryCache>(new ContainerControlledLifetimeManager());

i set cache in my homeController using following code

  var policy = new CacheItemPolicy();
  _cache.Set(key, value, policy);

but after uploading it to iis cache get empty sometime.

checking

        _cache.Get(key) **`it gets null`**

why its getting null? what should i do?


Solution

  • I find that MemoryCache is working by reference so if you do assign an object to memoryCache it will be by refremce

      _cache.Set(key, value, policy); //value should not be an object.
    

    you can use a serialize before caching the value so it can be done like

     var cloneValue = SerializationCloner.DeepFieldClone(value);