我如何可以使用的系统。网。缓存。高速缓存在一个控制台应用程序?
-
10-07-2019 - |
题
上下文:.净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);
}
结果是:
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
.谢谢你!
解决方案
Cache构造函数的文档说它仅供内部使用。要获取Cache对象,请调用HttpRuntime.Cache,而不是通过构造函数创建实例。
其他提示
虽然OP指定了v3.5,但是在v4发布之前问了这个问题。为了帮助发现此问题的任何人和能够使用v4依赖项,框架团队为此类场景创建了一个新的通用缓存。它位于System.Runtime.Caching命名空间中: http://msdn.microsoft.com/en -us /库/ dd997357%28V = VS.100%29.aspx
对默认缓存实例的静态引用是:MemoryCache.Default
我在这个页面上结束了想知道同样的事情。这就是我正在做的事情(我不喜欢,但似乎工作得很好):
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;
尝试
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);
}
该系统。网。缓存。缓类依赖于具有其成员"_cacheInternal"设定的HttpRuntime对象。
使用该系统。网。缓存课你必须创建一个HttpRuntime对象和设置HttpRuntime.高速缓存的财产。你会有效地得到仿效IIS。
你最好还是使用其他的高速缓存框架,如: