存储库模式 - 缓存
我不确定应该在存储库模式中的何处实现缓存。
我应该在服务逻辑中还是在存储库中实现它?
图形用户界面 ->业务逻辑(服务)->数据访问(存储库)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最好不要将缓存逻辑直接放入存储库中,因为这违反了单一职责原则 (SRP) 和关注点分离。 SRP 本质上表明你的类应该只有一个改变的理由。如果您将数据访问和缓存策略的关注点混为一谈,那么如果其中任何一个需要更改,您就需要接触该类。您还可能会发现您违反了 DRY 原则,因为很容易将缓存逻辑分布在许多不同的存储库方法中,并且如果其中任何一个需要更改,您最终将不得不更改许多方法。
更好的方法是使用代理或策略模式在单独的类型中应用缓存逻辑,例如 CachedRepository,然后当缓存为空时根据需要使用实际的以数据库为中心的存储库。我写了两篇文章,演示如何使用 .NET/C# 实现此功能,您可以在我的博客上找到这些文章:
如果您更喜欢视频,我还在 Pluralsight 上的代理设计模式中描述了该模式,此处:
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.