簡體   English   中英

在C#中實現DDD實體類

[英]Implementing DDD Entity class in C#

我現在開始使用DDD,我已經找到了一個很好的ValueObject實現,但是我似乎找不到實體的任何好的實現,我想要一個通用的基本實體類型,它將具有一個ID(規范需要)和實現當前的平等操作。

什么是最優雅的解決方案?

實體的唯一特征是它具有長壽和(半)永久身份。 您可以通過實現IEquatable<T>來封裝和表達它。 這是一種方法:

public abstract class Entity<TId> : IEquatable<Entity<TId>>
{
    private readonly TId id;

    protected Entity(TId id)
    {
        if (object.Equals(id, default(TId)))
        {
            throw new ArgumentException("The ID cannot be the default value.", "id");
        }

        this.id = id;
    }

    public TId Id
    {
        get { return this.id; }
    }

    public override bool Equals(object obj)
    {
        var entity = obj as Entity<TId>;
        if (entity != null)
        {
            return this.Equals(entity);
        }
        return base.Equals(obj);
    }

    public override int GetHashCode()
    {
        return this.Id.GetHashCode();
    }

    #region IEquatable<Entity> Members

    public bool Equals(Entity<TId> other)
    {
        if (other == null)
        {
            return false;
        }
        return this.Id.Equals(other.Id);
    }

    #endregion
}

為了實現正確的相等操作,我建議在Sharparchitecture查看域實體的基類 - https://github.com/sharparchitecture/Sharp-Architecture/blob/master/Solutions/SharpArch.Domain/DomainModel/EntityWithTypedId。 cs 它具有所有必需功能的實現。 並查看其他一些代碼,IMO,它對您和您的案例非常有用。

我不確定您是否遵循特定的庫/示例代碼或指南。 一個好的DDD解決方案將使用工廠進行實例化,與域模型分離的持久性(大多數ORM傾向於將兩者捆綁在一起),通過接口明確定義域邊界,強制字段和操作。

我強烈推薦Jimmy Nilson所着的“應用DDD和模式”一書。 它深入討論了DDD和最佳實踐。 這些示例也在C#中,適合您的項目。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM