0

My project using ASP.NET MVC5(.net 4.5.1) on Windows Server 2012 R2 IIS8.5

I have a class for get and set some cache

public class TheCache
    {
        #region Instance
        private static TheCache caches;
        private TheCache() { }

        public static TheCache Instance
        {
            get
            {
                if (null == caches)
                    caches = new TheCache();
                return caches;
            }
        }
        #endregion

      // Set the cache
      public void SetCache(key, data, time){
          MemoryCache.Default.Set(key, data, time);
       }

      // Get the cache
      public object GetCache(key){
          return MemoryCache.Default.Get(key);
       }

}

Now the problem is, I have a Action in a Controller

public ActionResult SomeActionInController(){
     //  this place always execute in every request
     if (null == TheCache.Instance.GetCache("key")
          TheCache.Instance.SetCache("key", "value", Datetime.Now.AddHours(1));
}

But I will get null in every requests. So Why? Is there any way to fixed it? Thank you.

Answer: Static property always null in every request after set value on ASP.NET MVC5

Community
  • 1
  • 1
qakmak
  • 1,287
  • 9
  • 31
  • 62

1 Answers1

1

Apart from the syntax issues, this code seems to run fine.

Here's the class I used:

public class TheCache
{
    // Set the cache
    public static void SetCache(string key, object data, DateTime time)
    {
        MemoryCache.Default.Set(key, data, time);
    }

    // Get the cache
    public static object GetCache(string key)
    {
        return MemoryCache.Default.Get(key);
    }
}

And here is the Action's code:

public ActionResult Index()
{ 
    if (null == TheCache.GetCache("key"))
        TheCache.SetCache("key", "value", DateTime.Now.AddHours(1));
    return View();
}
Aldracor
  • 2,133
  • 1
  • 19
  • 27
  • Yes, because I wirte it on here use my hand, not copy. When I debug there is also no problem. but when I deploy it to server, then the problem came. – qakmak Feb 09 '15 at 11:31
  • I changed my answer to be less complex that should work fine (it's the way we use it as well, "more or less") Unless you need the Instance for some other reason, take note of the static keyword on the functions – Aldracor Feb 10 '15 at 12:05
  • Thank you . but problem source is because the website restart by some reason, I put the answer on bottom. so no matter use static class or singlton, it always be lost the cache. but still thank you. – qakmak Feb 11 '15 at 06:00