could domain models be aware of repositories?

2020-07-15 05:08发布

May be for some domain logic implementation entities need access to repo for update/delete of self or any related entity. Does this sound right ??

2条回答
乱世女痞
2楼-- · 2020-07-15 05:34

While it definitely sounds dangerous for an entity to be able to access its own repository to store or delete itself (see persistence ignorance), in some particular cases I could tolerate that an entity exceptionnally requests from a Repository another aggregate root that it doesn't already hold a reference to.

However, note that domain entities should only know about abstractions of repositories (i.e. interfaces that reside in the domain layer) and not their concrete implementations. Therefore, don't have the Domain layer reference the Infrastructure layer, but instead inject instances of concrete repositories at runtime where you need them.

And this shouldn't be the norm, anyway.

查看更多
干净又极端
3楼-- · 2020-07-15 05:40

No, it doesn't, at least for the question tagged with "domain-driven-design" tag. Definitely, Active Record pattern has a right to live in some systems and some people find strong coupling useful, but in DDD the proposed way is to use repositories explicitly:

Evans DDD, p.152: For each type of object that needs global access, create an object that can provide the illusion of an in-memory collection of all objects of that type. «...» Provide REPOSITORIES only for AGGREGATE roots that actually need direct access. Keep the client focused on the model, delegating all object storage and access to the REPOSITORIES.

So, in DDD, repository not only encapsulates the infrastructure code, required to access the database, but the whole idea that the objects must be stored and loaded.

If you are doing some compound actions which involve saving and loading from the database, then the services that have references to the repositories are the best candidates.

查看更多
登录 后发表回答