Never use HttpContext to access the Cache!

This post was originally published on

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


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"]; 
blog comments powered by Disqus