聚合根引用其他聚合根 [英] Aggregate Root references other aggregate roots

查看:814
本文介绍了聚合根引用其他聚合根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用DDD进行很多工作,并且在从其他聚合根目录加载/操作聚合根目录时遇到问题.

I'm currently working a lot with DDD, and I'm facing a problem when loading/operating on aggregate roots from other aggregate roots.

对于模型中的每个聚合根,我也有一个存储库.该存储库负责处理根的持久性操作.

For each aggregate root in my model, I also have a repository. The repository is responsible for handling persistence operations for the root.

比方说,我有两个聚合根,其中有些成员(实体和值对象).

Let's say that I have two aggregate roots, with some members (entities and value objects).

AggregateRoot1和AggregateRoot2.

AggregateRoot1 and AggregateRoot2.

AggregateRoot1有一个引用AggregateRoot2的实体成员.

AggregateRoot1 has an entity member which references AggregateRoot2.

  1. 加载AggregateRoot1时,还应该加载AggregateRoot2吗?
  2. AggregateRoot2的存储库应对此负责吗?
  3. 如果是这样,AggregateRoot1中的实体可以调用AggregateRoot2的存储库进行加载吗?

此外,当我在AggregateRoot1中的实体与AggregateRoot2之间创建关联时,应该通过该实体还是通过AggregateRoot2的存储库来完成?

Also, when I create an association between the entity in AggregateRoot1 to AggregateRoot2, should that be done through the entity, or through the repository for AggregateRoot2?

希望我的问题有道理.

当前解决方案

Twith2Sugars 的帮助下,我想出了以下解决方案:

With help from Twith2Sugars I've come up with the following solution:

如问题中所述,聚合根可以包含引用其他根的子级.将root2分配给root1的成员之一时,root1的存储库将负责检测此更改,并将其委派给root2的存储库.

As described in the question, an aggregate root can have children that have references to other roots. When assigning root2 to one of the members of root1, the repository for root1 will be responsible for detecting this change, and delegating this to the repository for root2.

public void SomeMethod()
{
    AggregateRoot1 root1 = AggregateRoot1Repository.GetById("someIdentification");
    root1.EntityMember1.AggregateRoot2 = new AggregateRoot2();
    AggregateRoot1Repository.Update(root1);
}

public class AggregateRoot1Repository
{
    public static void Update(AggregateRoot1 root1)
    {
        //Implement some mechanism to detect changes to referenced roots
        AggregateRoot2Repository.HandleReference(root1.EntityMember1, root1.EntityMember1.AggregateRoot2)
    }
}

这只是一个简单的例子,不包含《得墨meter耳定律》或其他最佳原则/做法:-)

This is just a simple example, no Law of Demeter or other best principles/practices included :-)

更多评论表示赞赏.

推荐答案

也许在构造AggregateRoot1实体时,AggregateRoot1存储库可以调用AggregateRoot2存储库.

Perhaps the AggregateRoot1 repository could call AggregateRoot2 repository when it's constructing the the AggregateRoot1 entity.

我认为这不会使ddd无效,因为存储库仍负责获取/创建自己的实体.

I don't think this invalidates ddd since the repositories are still in charge of getting/creating their own entities.

这篇关于聚合根引用其他聚合根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆