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)
A cache repository is a storage location where Veeam Backup & Replication keeps temporary cached metadata for the data backed up by the file share backup jobs. For more information about cache repository, see NAS Backup Support.
The Repository pattern. Repositories are classes or components that encapsulate the logic required to access data sources. They centralize common data access functionality, providing better maintainability and decoupling the infrastructure or technology used to access databases from the domain model layer.
They decouple application and domain design from persistence technology, multiple database strategies, or even multiple data sources.
The idea behind the Repository pattern is to decouple the data access layer from the business access layer of the application so that the operations (such as adding, updating, deleting, and selecting items from the collection) is done through straightforward methods without dealing with database concerns such as ...
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:
I would handle it in the repository/data access layer. The reasoning is because it isn't up to the business layer on where to get the data from, that is the job of the repository. The repository will then decide where to get the data from, the cache (if it's not too old) or from the live data source based on the circumstances of the data access logic.
It's a data access concern more than a business logic issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With