Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Web.Caching.Cache throws null exception in a model

Maybe this question should be easy, but it is not. I have read Problem Using the System.Web.Caching.Cache Class in ASP.NET.

I have a singleton class:

private System.Web.Caching.Cache _cache;
private static CacheModel _instance = null;

private CacheModel() {
   _cache = new Cache();
}

public static CacheModel Instance {
         get {
            return _instance ?? new CacheModel();
         }
      }

public void SetCache(string key, object value){
   _cache.Insert(key, value);
}

If, anywhere else in my code, I call the following:

CacheModel aCache = CacheModel.Instance;
aCache.SetCache("mykey", new string[2]{"Val1", "Val2"});  //this line throws null exception

Why does the second line throw a null reference exception?

Maybe I have made some mistake somewhere in the code?

Thank you.

like image 911
Snake Eyes Avatar asked Dec 26 '22 16:12

Snake Eyes


1 Answers

You shouldn't use the Cache type to initialise your own instance:

This API supports the .NET Framework infrastructure and is not intended to be used directly from your code.

Without looking directly into why you would get a null reference exception, and I've ran into this problem before, this is tied in with the infrastructure and lifecycle of a web application:

One instance of this class is created per application domain, and it remains valid as long as the application domain remains active. Information about an instance of this class is available through the Cache property of the HttpContext object or the Cache property of the Page object.

Bottom line, don't use the System.Web.Caching.Cache type directly in this way - either access an existent cache instance or use an alternative like the Caching Application Block of the Enterprise Library.

like image 136
Grant Thomas Avatar answered Jan 18 '23 04:01

Grant Thomas