Never use HttpContext to access the Cache!

by Johan Driessen 28. November 2008 09:19

This has probably been said a million times, but it's definitely worth saying again. Never use HttpContext.Current.Cache, always use HttpRuntime.Cache. 

Why?

Because HttpRuntime is always available, even when you're not in a web context (e.g. even in a console app), and HttpContext is not. And it's the exact same Cache! Do you, for example, think that you have access to the HttpContext in a unit test? Probably not. HttpRuntime? Of course! 

So, to sum it up:

//Bad code
return HttpContext.Current.Cache["myitem"];
//Good code
return HttpRuntime.Cache["myitem"];

Tags: ,

Development

blog comments powered by Disqus

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.


Welcome to the Dropit blog!

Here we, the people that work at Dropit, will write about stuff that interests us. For example web development, especially with .NET and EPiServer - but we'll also talk about other techniques that interest us, marketing on the web, social phenomenons, pop culture, games and software development in general.