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

六月ゝ 毕业季﹏ 提交于 2019-12-07 08:53:49

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12746626/system-web-caching-cache-throws-null-exception-in-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!