Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 359
Ron Klein Avatar asked Jun 24 '09 11:06

Ron Klein


People also ask

How do I use .NET cache?

To manually cache application data, you can use the MemoryCache class in ASP.NET. ASP.NET also supports output caching, which stores the generated output of pages, controls, and HTTP responses in memory. You can configure output caching declaratively in an ASP.NET Web page or by using settings in the Web. config file.

How caching is done in ASP.NET explain with example?

Caching is a technique of storing frequently used data/information in memory, so that, when the same data/information is needed next time, it could be directly retrieved from the memory instead of being generated by the application.


2 Answers

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.

like image 191
Amit G Avatar answered Oct 13 '22 05:10

Amit G


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

like image 29
Joel Fillmore Avatar answered Oct 13 '22 07:10

Joel Fillmore