2009-06-24 106 views
29

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

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

,其结果是:

 
cannot insert to cache, exception: 
System.NullReferenceException: Object reference not set to an instance of an object. 
    at System.Web.Caching.Cache.Insert(String key, Object value) 
    at MyClass.RunSnippet() 

所以,很显然,我在这里做得不对。有任何想法吗?


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

回答

56

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

9

只要使用Caching Application Block,如果你不想重新发明轮子。如果您仍想使用ASP.NET缓存 - see here。我很确定这只适用于.NET 2.0及更高版本。这根本是不可能的使用ASP.NET缓存之外的.NET 1

MSDN有缓存文件过多的页面上一个漂亮的大警告:

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

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

+0

“看这里”链接被打破 – 2009-06-24 11:52:04

+0

@罗恩 - 这是一个错误#1。下面是同一个链接的TinyUrl:http://tinyurl.com/ms35eu – RichardOD 2009-06-24 13:20:47

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

1

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

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

你最好不要使用其他缓存框架,如:

+1

“通过内部方法设置的唯一方法” - 不是true,_cacheInternal由静态属性访问器HttpRuntime.Cache设置。然而,我会对更多关于为什么MSDN建议ASP.NET缓存不应该用于非web应用的信息感兴趣。我有使用它的代码(它来自此警告存在之前的日期),并且它似乎*可以正常工作。 – Joe 2009-06-24 16:52:16

+0

谢谢@Joe - 编辑我的答案 – d4nt 2009-06-29 09:05:39

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; 
28

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

静态参考默认缓存实例是:MemoryCache.Default

相关问题