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

Posted by Ron Klein on Stack Overflow See other posts from Stack Overflow or by Ron Klein
Published on 2009-06-24T11:06:39Z Indexed on 2010/05/05 8:08 UTC
Read the original article Hit count: 352

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!

© Stack Overflow or respective owner

Related posts about .NET

Related posts about cache