Never use HttpContext to access the Cache! | Johan Driessen

Never use HttpContext to access the Cache!

This post was originally published on http://labs.dropit.se/blogs.

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:

1
2
3
4
5
//Bad code
return HttpContext.Current.Cache["myitem"];

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