[英]Can I create repository by data source or should I create a repository by aggregate?
Right now I'm implementing repository pattern on my project, and I have doubts about how exactly should I implement repository pattern.现在我正在我的项目上实现存储库模式,我对我到底应该如何实现存储库模式有疑问。 My idea was to create repository by data source, eg RedisRepository, DbRepository.
我的想法是通过数据源创建存储库,例如RedisRepository、DbRepository。 And I have not found any strict rules on what repository should be based.
而且我还没有找到关于应该基于什么存储库的任何严格规则。
So my question is it a good practice to create repository based on data source, or in any case the best practice is to create repository by aggregate eg CarRepository?所以我的问题是基于数据源创建存储库是一种好的做法,或者无论如何最好的做法是通过聚合(例如 CarRepository)创建存储库? Maybe you can also share some nice articles related to this topic, if you know ones.
如果您知道的话,也许您还可以分享一些与此主题相关的好文章。
If you're adopting the domain-driven design approach, you should have a repository for each aggregate root: https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/infrastructure-persistence-layer-design .如果您采用域驱动设计方法,则每个聚合根都应该有一个存储库: https ://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ 基础设施持久层设计。
Within Hexagonal architecture, the standard way to do this would be like so:在 Hexagonal 架构中,执行此操作的标准方法如下:
Application layer defines the repository interface (eg what it needs) and here you intentionally omit any persistence technology details, because it doesn't care how the functionality is provided.应用层定义了存储库接口(例如它需要什么),在这里您有意省略了任何持久性技术细节,因为它不关心功能是如何提供的。 It might look like this:
它可能看起来像这样:
interface CarPersistence {
update(car);
findOne(model, brand, ...);
}
In your Infrastructure layer , you will create a repository implementation for a specific persistence technology that will implement this interface, thus providing the required functionality to the application layer.在您的基础设施层中,您将为特定的持久性技术创建一个存储库实现,该技术将实现此接口,从而为应用程序层提供所需的功能。 This implementation defines how the needed functionality is provided.
该实现定义了如何提供所需的功能。
class MongoDbCarPersistence implements CarPersistence {
// ...
}
The key aspect is that the interface definition in the Application layer is technology agnostic.关键方面是应用层中的接口定义与技术无关。 So whether you implement the actual repository for MongoDB or MySQL would have no impact on the interface, and therefore on any class using that interface.
因此,无论您是为 MongoDB 还是 MySQL 实现实际存储库,都不会影响接口,因此不会影响使用该接口的任何类。 This is one of the main purposes of Hexagonal architecture.
这是六角形建筑的主要目的之一。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.