Ron*_*ein 29 .net caching console-application httpcontext
上下文:.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);
}
Run Code Online (Sandbox Code Playgroud)
结果是:
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.谢谢你们!
Joe*_*ore 28
虽然OP指定了v3.5,但是在v4发布之前就提出了这个问题.为了帮助发现此问题并且可以使用v4依赖项的任何人,框架团队为此类场景创建了一个新的通用缓存.它位于System.Runtime.Caching命名空间中:http: //msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx
对默认缓存实例的静态引用是:MemoryCache.Default