Is injecting repository in aggregate root / entity considered bad design?

浪子不回头ぞ 提交于 2019-12-24 22:32:16

问题


I am trying to learn about details of domain driven design and i came to this question. I found many examples with:

  1. Defining repository interface within the domain
  2. Defining repository implementation somewhere else
  3. Inject repository interface into aggregate root

On the other hand, there are examples that strictly go against it and do all repository related stuff from service.

I cannot find authoritive answer and explanation: is it considered a bad practice and if so - why?


回答1:


I cannot find authoritive answer and explanation: is it considered a bad practice and if so - why?

Yes, mostly because a number of different concerns get confused.

Aggregates define a consistency boundary; any change of state should be restricted to a collection of related entities that are all part of the same aggregate. So once you have looked up the first one (the "root" entity), you should be able to achieve the change without needing to examine any data other than this graph of domain entities and the arguments that you have been passed.

Put another way, Repository is a plumbing concern, not a domain concern. Your domain entities are responsible for expressing your domain, without infrastructure concerns getting mixed in.

To have, for example, Aggregate.Save() method that would inside use IRepository interface to save.

Aggregate.Save() definitely indicates a problem. Well, two problems, to be precise: Save probably isn't part of your ubiquitous language, and for that matter its likely that Aggregate isn't either.

Save isn't a domain concern, it's a persistence concern - it just copies data from your in memory representation (volatile storage) to a durable representation (stable storage). Your domain model shouldn't need to know anything about that.

One of the reasons you found "many examples with" is that getting these concerns separated correctly is hard; meaning you really need to think deeply about the problem to tease them apart. Most examples don't, because teasing things apart isn't critical when you always deploy everything together.



来源:https://stackoverflow.com/questions/47856245/is-injecting-repository-in-aggregate-root-entity-considered-bad-design

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