.net 如何在控制台应用程序中使用 System.Web.Caching.Cache?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1037695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 12:54:58  来源:igfitidea点击:

How can I use System.Web.Caching.Cache in a Console application?

.netcachingconsole-applicationhttpcontext

提问by Ron Klein

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.Cacheis supposed to run only in a valid HTTP context. My very simple snippet looks like this:

上下文:.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);
}

and the result is:

结果是:

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?

很明显,我在这里做错了。有任何想法吗?



Update: +1 to most answers, getting the cache via static methods is the correct usage, namely HttpRuntime.Cacheand HttpContext.Current.Cache. Thank you all!

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

回答by Amit G

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.

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

回答by Joel Fillmore

While the OP specified v3.5, the question was asked before v4 was released. To help anyone who finds this question andcan live with a v4 dependency, the framework team created a new general purpose cache for this type of scenario. It's in the System.Runtime.Caching namespace: http://msdn.microsoft.com/en-us/library/dd997357%28v=VS.100%29.aspx

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

The static reference to the default cache instance is: MemoryCache.Default

默认缓存实例的静态引用是:MemoryCache.Default

回答by RichardOD

Just use the Caching Application Blockif you don't want to reinvent the wheel. If you still want to use the ASP.NET cache- see here. I'm pretty sure this only works with .NET 2.0 and above though. It simply wasn't possible to use the cache outside of ASP.NET in .NET 1.

如果您不想重新发明轮子,只需使用缓存应用程序块。如果您仍想使用 ASP.NET 缓存 -请参见此处。我很确定这仅适用于 .NET 2.0 及更高版本。在 .NET 1 中,不可能在 ASP.NET 之外使用缓存。

MSDN has a nice big warning on the page for the cache documentation too:

MSDN 在缓存文档页面上也有一个很好的警告:

The Cache class is not intended for use outside of ASP.NET applications. It was designed and tested for use in ASP.NET to provide caching for Web applications. In other types of applications, such as console applications or Windows Forms applications, ASP.NET caching might not work correctly.

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

For a very lightweight solution, where you don't have to worry about expiration etc, then a dictionary object could suffice.

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

回答by Jim Rogers

I ended on this page wondering the same thing. Here's what I'm doing (which I don't like but seems to work just fine):

我在这个页面结束时想知道同样的事情。这是我正在做的事情(我不喜欢但似乎工作得很好):

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;

回答by Hans Malherbe

Try

尝试

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

回答by d4nt

The System.Web.Caching.Cache class relies on having its member "_cacheInternal" set by the HttpRuntime object.

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

To use the System.Web.Caching classes you'd have to create an HttpRuntime object and setup the HttpRuntime.Cache property. You'd effectively have to emulate IIS.

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

You're better off using other caching frameworks like:

您最好使用其他缓存框架,例如: