如果我理解您的尝试,您正在向相关 IList 添加一个 Comment(),该 IList 附加到 Post()。在您的 Post() 中,您正在 IList 中寻找任何新的 Comment() 并保存它们。让 Post() 对象控制它的子对象,例如 Comment(),确实走上了 DDD 的道路。
我自己对这些模式还是陌生的;但就个人而言,我倾向于认为任何具有元数据的实体,我都将其视为自己的实体模型;因此,我为每个实体模型创建了自己的存储库。
Post()
PostRepository : IPostRepository
Comment()
CommentRepository : ICommentRepository
现在,我认为拥有 IList Post.Comments 违反了得墨忒耳定律,因为它允许您执行 Post.Comments.Add()。
我相信您的问题的解决方案不会添加到 IList,而是在 Post() 上创建方法来处理与该 Post 实例相关的评论:
Post.AddComment()
Post.FetchComments()
Post.DeleteComments(IList<Comment> comments)
然后在 Post() 对象中,连接 ICommentRepository(很可能使用 ServiceLocator,或者我更喜欢 Castle Windsor)并处理它们的添加和删除。
ICommentRepository.AddByPostID()
ICommentRepository.FetchByPostID()
ICommentRepository.Remove(int commentID)
同样,我对 DDD 模式还是很陌生;但是,我相信这是保持关注点分离有效并通过将其保持在 Post() 的关注范围内来掩盖底层逻辑,以“仅处理与此 Post 对象相关的评论的操作”。
完整的 Post() 类将是这样的:
private ICommentRepository _commentRepo;
public class Post
{
public Post(ICommentRepository commentRepo)
{
// Or you can remove this forced-injection and use a
// "Service Locator" to wire it up internall.
_commentRepo = commentRepo;
}
public int PostID { get; set; }
public void DeleteComments(IList<Comment> comments)
{
// put your logic here to "lookup what has been deleted"
// and then call ICommentRepository.Delete() in the loop.
_commentRepo.Remove(commentID);
}
}
如果其他人有意见或变化,请发表评论。