Dependencies between domain object, factory and repository

ε祈祈猫儿з 提交于 2019-11-29 04:30:42
theDmi

You've got the basics right. The misunderstanding you have seems to come from your assumption that domain objects should be the primary clients of repositories. This is not the case, you should only access the repositories from domain objects if there is no other way. Try to avoid it in general.

So the missing piece in your equation is the thing that acts as primary client of the repositories.

Enter: The Application Service

An application service is a service that contains use case logic (as opposed to domain logic). It performs input validation, implements access management, and is responsible for transaction control.

This means the app service would use a repository to load an aggregate from the DB, do something with it, and then make sure the changes are persisted (i.e. commit the transaction).

Depending on the style of repository that you're using, saving an aggregate back to the DB is slightly different:

  • With collection-style repositories, the app service normally uses a unit of work to track and commit the changes.
  • With command-style repositories, the app service passes the aggregate back to the repository after performing the business operation on it.

Factories and Repositories

Regarding your questions about the relationship between factories and repositories, I think this answer of mine provides the answer to your question as well. The basic gist of it is:

  • Use the factory from the repository to avoid duplicating the instantiation logic of an aggregate.
  • Make sure the concepts are clear from the outside, i.e. don't expose the "reconsitution interface" of a factory that the repository sees to other classes. This is best achieved by following the Interface Segregation Principle.

Using Repositories from the Domain

If you constantly need to query other aggregates from the DB to perform business tasks in the domain layer, this is an indication that your aggregate boundaries could be wrong.

Of course, there are cases where the aggregate boundaries are fine, and the required objects cannot be passed to the domain object as parameter. In that case, it can make sense to use a repository from the domain. Be sure to try other approaches before doing this. In any case, only depend on a repository interface, never on a concrete repository implementation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!