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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With