我怎样才能在一个控制台应用程序中使用的System.Web.Caching.Cache? [英] How can I use System.Web.Caching.Cache in a Console application?
问题描述
上下文:3.5的.Net,C#
我想有缓存机制在我的控制台应用程序。
而不是重新发明轮子,我想使用的System.Web.Caching.Cache
(这是最后的决定,我不能用其他的缓存框架,不要问为什么)。
不过,它看起来像的System.Web.Caching.Cache
应该只在一个有效的HTTP上下文中运行。我非常简单的代码段看起来是这样的:
Context: .Net 3.5, C#
I'd like to have caching mechanism in my Console application.
Instead of re-inventing the wheel, I'd like to use System.Web.Caching.Cache
(and that's a final decision, I can't use other caching framework, don't ask why).
However, it looks like System.Web.Caching.Cache
is supposed to run only in a valid HTTP context. My very simple snippet looks like this:
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()
所以,很显然,我在这里做了什么。任何想法?
So obviously, I'm doing something wrong here. Any ideas?
更新:+1大多数的答案,通过静态方法获取缓存是正确的用法,即 HttpRuntime.Cache
和 HttpContext.Current.Cache
。谢谢大家!
Update: +1 to most answers, getting the cache via static methods is the correct usage, namely HttpRuntime.Cache
and HttpContext.Current.Cache
. Thank you all!
推荐答案
的说明文件缓存构造说,这是仅供内部使用。为了让您的高速缓存对象,调用HttpRuntime.Cache而不是通过构造函数创建一个实例。
The documentation for the Cache constructor says that it is for internal use only. To get your Cache object, call HttpRuntime.Cache rather than creating an instance via the constructor.
这篇关于我怎样才能在一个控制台应用程序中使用的System.Web.Caching.Cache?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!