How to implement a caching model without violating MVC pattern?

Posted by RPM1984 on Stack Overflow See other posts from Stack Overflow or by RPM1984
Published on 2011-02-06T22:38:08Z Indexed on 2011/02/06 23:25 UTC
Read the original article Hit count: 198

Hi Guys,

I have an ASP.NET MVC 3 (Razor) Web Application, with a particular page which is highly database intensive, and user experience is of the upmost priority.

Thus, i am introducing caching on this particular page.

I'm trying to figure out a way to implement this caching pattern whilst keeping my controller thin, like it currently is without caching:

public PartialViewResult GetLocationStuff(SearchPreferences searchPreferences)
{
   var results = _locationService.FindStuffByCriteria(searchPreferences);
   return PartialView("SearchResults", results);
}

As you can see, the controller is very thin, as it should be. It doesn't care about how/where it is getting it's info from - that is the job of the service.

A couple of notes on the flow of control:

  1. Controllers get DI'ed a particular Service, depending on it's area. In this example, this controller get's a LocationService
  2. Services call through to an IQueryable<T> Repository and materialize results into T or ICollection<T>.

How i want to implement caching:

  • I can't use Output Caching - for a few reasons. First of all, this action method is invoked from the client-side (jQuery/AJAX), via [HttpPost], which according to HTTP standards should not be cached as a request. Secondly, i don't want to cache purely based on the HTTP request arguments - the cache logic is a lot more complicated than that - there is actually two-level caching going on.
  • As i hint to above, i need to use regular data-caching, e.g Cache["somekey"] = someObj;.
  • I don't want to implement a generic caching mechanism where all calls via the service go through the cache first - i only want caching on this particular action method.

First thought's would tell me to create another service (which inherits LocationService), and provide the caching workflow there (check cache first, if not there call db, add to cache, return result).

That has two problems:

  1. The services are basic Class Libraries - no references to anything extra. I would need to add a reference to System.Web here.
  2. I would have to access the HTTP Context outside of the web application, which is considered bad practice, not only for testability, but in general - right?

I also thought about using the Models folder in the Web Application (which i currently use only for ViewModels), but having a cache service in a models folder just doesn't sound right.

So - any ideas? Is there a MVC-specific thing (like Action Filter's, for example) i can use here?

General advice/tips would be greatly appreciated.

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc