上下文:.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.Cache
和HttpContext.Current.Cache
。谢谢你们!
“看这里”链接被打破 – 2009-06-24 11:52:04
@罗恩 - 这是一个错误#1。下面是同一个链接的TinyUrl:http://tinyurl.com/ms35eu – RichardOD 2009-06-24 13:20:47