views:

626

answers:

2

So, I was looking over my standard cache utility when preparing to unit test a controller and thought, hey, is accessing the HttpRuntime.Cache directly considered harmful in MVC?

I wrap the cache in a proxy class that implements a cache-like interface (tho much simpler) so that I can mock it during tests. But I'm wondering if that's already done for me in the new framework. I can't find anything, however.

Here's an idea of how I do it:

public ActionResult DoStuffLol(guid id)
{
  var model = CacheUtil.GetOrCreateAndStore(
                  "DoStuffLolModel",
                  () =>
                  {
                    /* construct model here; time consuming stuff */
                    return model;
                  });
  return View("DoStuffLol", model);
}

So, has the old patterns of accessing the cache changed? Are there any better patterns for caching action results in MVC?

+1  A: 

Add the OutputCache attribute to your controller action in order to tell the framework to cache the output for you. You can read more about this attribute in ScottGu's blog post on ASP.NET Preview 4.

Don't combine this with the Authorize attribute, however.

Craig Stuntz
This is only for caching the entire controller action. To cache just pieces of data the mechanics haven't changed in ASP.Net MVC.
Sean Carpenter
A: 

No, but the cache has changed in 3.5. 3.5 includes wrapper classes that make stubbing/mocking many of the static classes used in asp.net easy.

http://www.codethinked.com/post/2008/12/04/Using-SystemWebAbstractions-in-Your-WebForms-Apps.aspx

Will