29

上下文:.Net 3.5,C#
我想在我的控制台应用程序中有缓存机制。
而不是重新发明轮子,我想使用System.Web.Caching.Cache(这是最终决定,我不能使用其他缓存框架,不要问为什么)。
但是,它看起来System.Web.Caching.Cache应该只在有效的 HTTP 上下文中运行。我非常简单的代码片段如下所示:

using System;
using System.Web.Caching;
using System.Web;

Cache c = new Cache();

try
{
    c.Insert("a", 123);
}
catch (Exception ex)
{
    Console.WriteLine("cannot insert to cache, exception:");
    Console.WriteLine(ex);
}

结果是:

无法插入缓存,异常:
System.NullReferenceException:对象引用未设置为对象的实例。
   在 System.Web.Caching.Cache.Insert(字符串键,对象值)
   在 MyClass.RunSnippet()

很明显,我在这里做错了什么。有任何想法吗?


更新:对大多数答案+1,通过静态方法获取缓存是正确的用法,即HttpRuntime.Cacheand HttpContext.Current.Cache。谢谢你们!

4

6 回答 6

56

Cache 构造函数的文档说它仅供内部使用。要获取您的 Cache 对象,请调用 HttpRuntime.Cache 而不是通过构造函数创建实例。

于 2009-06-24T11:23:21.047 回答
28

虽然 OP 指定了 v3.5,但在 v4 发布之前就提出了这个问题。为了帮助任何发现这个问题并且可以忍受 v4 依赖的人,框架团队为这种类型的场景创建了一个新的通用缓存。它位于 System.Runtime.Caching 命名空间中:http: //msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

默认缓存实例的静态引用是:MemoryCache.Default

于 2010-05-05T08:05:20.707 回答
9

如果您不想重新发明轮子,只需使用缓存应用程序块。如果您仍想使用 ASP.NET 缓存,请参见此处。我很确定这仅适用于 .NET 2.0 及更高版本。根本不可能在 .NET 1 中使用 ASP.NET 之外的缓存。

MSDN 在缓存文档的页面上也有一个很好的警告:

Cache 类不适合在 ASP.NET 应用程序之外使用。它是为在 ASP.NET 中使用而设计和测试的,以便为 Web 应用程序提供缓存。在其他类型的应用程序中,例如控制台应用程序或 Windows 窗体应用程序,ASP.NET 缓存可能无法正常工作。

对于一个非常轻量级的解决方案,您不必担心过期等问题,那么字典对象就足够了。

于 2009-06-24T11:13:09.490 回答
4

我在这个页面上结束了同样的事情。这就是我正在做的事情(我不喜欢但似乎工作得很好):

HttpContext context = HttpContext.Current;
if (context == null)
{
    HttpRequest request = new HttpRequest(string.Empty, "http://tempuri.org", string.Empty);
    HttpResponse response = new HttpResponse(new StreamWriter(new MemoryStream()));
    context = new HttpContext(request, response);
    HttpContext.Current = context;
}
this.cache = context.Cache;
于 2010-02-01T22:49:04.723 回答
1

尝试

public class AspnetDataCache : IDataCache
{
    private readonly Cache _cache;

    public AspnetDataCache(Cache cache)
    {
        _cache = cache;
    }

    public AspnetDataCache()
        : this(HttpRuntime.Cache)
    {

    }
    public void Put(string key, object obj, TimeSpan expireNext)
    {
        if (key == null || obj == null)
            return;
        _cache.Insert(key, obj, null, DateTime.Now.Add(expireNext), TimeSpan.Zero);
    }

    public object Get(string key)
    {
        return _cache.Get(key);
    }

于 2009-06-24T11:25:29.840 回答
1

System.Web.Caching.Cache 类依赖于由 HttpRuntime 对象设置其成员“_cacheInternal”。

要使用 System.Web.Caching 类,您必须创建一个 HttpRuntime 对象并设置 HttpRuntime.Cache 属性。您实际上必须模拟 IIS。

您最好使用其他缓存框架,例如:

于 2009-06-24T11:28:35.310 回答