Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

As Grant noted above the System.web.caching.cache stores ASP.NET internal data (like bundles that have been built in the App_start).

Use the System.Runtime.Caching instead. here's the walkthrough on MSDN

Here's a snippet: `

using System.Runtime.Caching;

...

ObjectCache cache = MemoryCache.Default;
var test = "hello world";
cache["greeting"] = test;
var greeting = (string)cache["greeting"];

`

In ASP.NET 4, caching is implemented by using the ObjectCache class. read more on MSDN

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top