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

发布于 2024-07-25 18:42:09 字数 872 浏览 4 评论 0原文

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

结果是:

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.CacheHttpContext.Current.Cache 。 谢谢你们!

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

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.Cache and HttpContext.Current.Cache. Thank you all!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

扬花落满肩 2024-08-01 18:42:09

Cache 构造函数的文档表明它仅供内部使用。 要获取 Cache 对象,请调用 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.

水染的天色ゝ 2024-08-01 18:42:09

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

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

While the OP specified v3.5, the question was asked before v4 was released. To help anyone who finds this question and can 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

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

梦幻的心爱 2024-08-01 18:42:09

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

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

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

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

Just use the Caching Application Block if 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.

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

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.

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

情何以堪。 2024-08-01 18:42:09

我在这一页结束时也想知道同样的事情。 这就是我正在做的事情(我不喜欢,但似乎效果很好):

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;

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;
夜深人未静 2024-08-01 18:42:09

尝试

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

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

你是年少的欢喜 2024-08-01 18:42:09

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

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

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

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

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.

You're better off using other caching frameworks like:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文