【问题标题】:System.Web.Caching.Cache throws null exception in a modelSystem.Web.Caching.Cache 在模型中引发空异常
【发布时间】:2012-09-26 15:10:00
【问题描述】:

也许这个问题应该很容易,但事实并非如此。我读过Problem Using the System.Web.Caching.Cache Class in ASP.NET

我有一个单例类:

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);
}

如果在我的代码中的其他任何地方,我会调用以下代码:

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

为什么第二行会抛出空引用异常?

也许我在代码的某个地方犯了一些错误?

谢谢。

【问题讨论】:

    标签: c# asp.net-mvc-3 caching data-caching


    【解决方案1】:

    你不应该使用Cache类型to initialise your own instance

    此 API 支持 .NET Framework 基础结构,不能直接从您的代码中使用。

    不直接查看为什么你会得到一个空引用异常,我之前遇到过这个问题,这是tied in with the infrastructure and lifecycle of a web application

    每个应用程序域都会创建一个此类的实例,只要应用程序域保持活动状态,它就会保持有效。有关此类实例的信息可通过 HttpContext 对象的 Cache 属性或 Page 对象的 Cache 属性获得。

    最重要的是,不要以这种方式直接使用 System.Web.Caching.Cache 类型 - 要么访问现有的缓存实例,要么使用类似 Caching Application Block of the Enterprise Library 的替代方法。

    【讨论】:

      【解决方案2】:

      如上所述,System.web.caching.cache 存储 ASP.NET 内部数据(如已在 App_start 中构建的包)。

      改用 System.Runtime.Cachinghere's the walkthrough on MSDN

      这是一个sn-p: `

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

      `

      在 ASP.NET 4 中,缓存是通过使用 ObjectCache 类实现的。 read more on MSDN

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-26
        相关资源
        最近更新 更多