避免在域模型循环引用 [英] Avoid circular reference in domain model

查看:134
本文介绍了避免在域模型循环引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这必须是一个常见的​​场景,有已经有很多写它了,希望即使一个很好的模式。予具有其中一个自定义的容器中包含的实体域模型。例如(属性和接口排除简洁):

 实体类
{
    公众诠释标识;
    公共EntityContainer相关ParentContainer;
}


类EntityContainer相关
{
    公众诠释标识;
    公众的IList<实体>实体=新的名单,其中,实体>();

    公共无效AddEntity(实体实体)
    {
        entity.ParentContainer =这一点;
        Entities.Add(实体);
    }
}


一流的主
{
    公众的Main()
    {
        实体使用实体=新实体();
        实体实体2 =新实体();
        EntityContainer相关EntityContainer相关=新EntityContainer相关();
        entityContainer.AddEntity(使用实体);
        entityContainer.AddEntity(实体2);

        //现在能遍历图轻松,例如
        Console.WriteLine(使用实体的父容器ID =+ entity1.ParentContainer.Id);
        Console.WriteLine(容器至少包含该实体ID:+ entityContainer.Entities [0] .ID);

    }
}
 

我现在可以很容易地遍历我的对象图左右逢源,但已经创建了一个循环引用。你会创建一个第三类离婚的依赖?

在此先感谢

解决方案

这没有什么错循环引用,本身,它们广泛用于.NET框架,如XmlNode.OwnerDocument,Control.Parent。

如果您需要遍历了树,然后反向引用是蛮好用的。<​​/ P>

在COM,循环引用是棘手,因为如果你的设置容器及其所有子事,那么对象不会被清理正确的孩子仍持有引用到父。然而,.NET垃圾收集与这一点,执行的方式没有问题。

this must be such a common scenario that there's been a lot written about it already, hopefully even a really good pattern. I have a domain model in which a custom container contains entities. For example (properties and interfaces excluded for brevity):

class Entity
{
    public int Id;
    public EntityContainer ParentContainer;
}


class EntityContainer
{
    public int Id;
    public IList<Entity> Entities = new List<Entity>();

    public void AddEntity(Entity entity)
    {
        entity.ParentContainer = this;
        Entities.Add(entity);
    }
}


class Main
{
    public Main()
    {
        Entity entity1 = new Entity();
        Entity entity2 = new Entity();
        EntityContainer entityContainer = new EntityContainer();
        entityContainer.AddEntity(entity1);
        entityContainer.AddEntity(entity2);

        // Can now traverse graph easily, e.g.
        Console.WriteLine("entity1's parent container ID = " + entity1.ParentContainer.Id);
        Console.WriteLine("Container contains at least this entity ID: " + entityContainer.Entities[0].Id);

    }
}

I can now easily traverse my object graph both ways, but have created a circular reference. Would you create a third type to divorce the dependencies?

Thanks in advance

解决方案

There's nothing wrong with circular references, per se, and they are used extensively in the .NET Framework, e.g. XmlNode.OwnerDocument, Control.Parent.

If you need to traverse up the tree, then a back reference is fine to use.

In COM, circular references are tricky because if you were the set the container and all its children to nothing, then objects will not be cleaned up properly as the children still hold references to the parent. However the .NET garbage collection has no problem with this the way it is implemented.

这篇关于避免在域模型循环引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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