how should i add an object into a collection maintained by aggregate root

假如想象 提交于 2019-12-29 05:16:25

问题


lets say i have a BlogPost aggregate root. it holds a List<Comment>.
how should the BlogPost AddComment signature look? is it OK to use:

public void AddComment(Comment comment)
{
    Comments.Add(comment);
}

or should i avoid creating references to root's children outside of it, and do something like this:

public void AddComment(string text, string email)
{
    Comment comment = new Comment(text, email);
    Comments.Add(comment);
}

回答1:


If you believe in DDD, it's perfectly fine to know about some entity beneath the aggregate root, as long as you do not store an ID or a reference to it somewhere outside of the aggregate.

I would go for the blogPost.AddComment(new Comment(...))-version.




回答2:


If you consider Comment to be an aggregate of BlogPost and to not make sense out of that scope then you should be using the second example.

The aggregate root should control how the aggregates are instantiated so their constructors should not be visible outside of the aggregate root.

Plus, Comment should be a child class of BlogPost if you want a true relation of AggregateRoot-Aggregate.



来源:https://stackoverflow.com/questions/566854/how-should-i-add-an-object-into-a-collection-maintained-by-aggregate-root

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