views:

1961

answers:

2

I have an MVC-based site, which is using a Repository/Service pattern for data access. The Services are written to be using in a majority of applications (console, winform, and web). Currently, the controllers communicate directly to the services. This has limited the ability to apply proper caching.

I see my options as the following:

  • Write a wrapper for the web app, which implements the IWhatEverService which does caching.
  • Apply caching in each controller by cache the ViewData for each Action.
  • Don't worry about data caching and just implement OutputCaching for each Action.

I can see the pros and cons of each. What is/should the best practice be for caching with Repository/Service

+4  A: 

The easiest way would be to handle caching in your repository provider. That way you don't have to change out any code in the rest of your app; it will be oblivious to the fact that the data was served out of a cache rather than the repository.

So, I'd create an interface that the controllers use to communicate with the backend, and in the implementation of this I'd add the caching logic. Wrap it all up in a nice bow with some DI, and your app will be set for easy testing.

Will
How can I do this and keep the Repositories and Services agnostic? I would like to reuse the R/S for other non-web applications.
LaptopHeaven
Hmmm.... I don't see an issue here. You can create a standard Repository or a CacheableRepository that takes an ICache dependency (whatever that may be). Just because you're "caching" doesn't mean you MUST use httpcache
Will
Will
+1  A: 

Check my implementation of caching service:
http://stackoverflow.com/questions/343899/how-to-cache-data-in-a-mvc-application#349111
(i don't want to repeat answer here...)
Fell free to comment!

Hrvoje