Repository Pattern - Caching

Beni picture Beni · Aug 9, 2010 · Viewed 13.9k times · Source

I'm not sure where I should implement the caching in my repository pattern.

Should I implement it in the service-logic or in the repository?

GUI -> BusinessLogic (Services) -> DataAccess (Repositories)

Answer

ssmith picture ssmith · Oct 18, 2011

It's a good idea not to put the caching logic directly into your repository, as that violates the Single Responsibility Principle (SRP) and Separation of Concerns. SRP essentially states that your classes should only have one reason to change. If you conflate the concerns of data access and caching policy in the same class, then if either of these needs to change you'll need to touch the class. You'll also probably find that you're violating the DRY principle, since it's easy to have caching logic spread out among many different repository methods, and if any of it needs to change, you end up having to change many methods.

The better approach is to use the Proxy or Strategy pattern to apply the caching logic in a separate type, for instance a CachedRepository, which then uses the actual db-centric repository as needed when the cache is empty. I've written two articles which demonstrate how to implement this using .NET/C#, which you will find on my blog, here:

If you prefer video, I also describe the pattern in the Proxy Design Pattern on Pluralsight, here: