根據前面對領域驅動設計概念以及一些最佳實踐的理解,領域模型是系統最核心的部分,我們還是采用前面銷售訂單的例子,這個案例系統的核心構建就從領域層開始。領域層框架搭建主要完成兩個任務:
1.領域模型的建立,聚合與聚合根的確定,關系的確定。
2.建立支持DDD理論的領域層接口。
這里先上代碼圖,再詳細講每個部分的主要功能:

1.Model中主要確定了領域對象,聚合與聚合根,關聯關系等,我們這里采用的是EF 的Model First建模,你也可以采取Code First。如下圖:

2.Aggreate中主要定義了兩個接口,一個是IEntity,一個是IAggreateRoot,分別表示實體與聚合根。我這里直接用表未來的GUID主鍵作為實體的唯一標識符
using System; namespace Order.Domain.Aggreate { public interface IEntity { Guid Id { get; } } }
namespace Order.Domain.Aggreate { public interface IAggreateRoot:IEntity { } }
3.Repository中主要定義了IRepository與IRepositoryContext接口。
將IRepository接口定義在領域層的主要目的是:
1)領域層不應該直接依賴於倉儲實現:如果領域層依賴於倉儲實現,一是技術綁定太緊密,二是倉儲要對領域對象作操作,會造成循環依賴。
2)將接口定義在領域層,減少技術架構依賴,應用層或領域層要使用某個倉儲實現時,通過依賴注入的方式將倉儲實現注射到應用層或領域層,具體IOC在使用時對應用層與領域層的建議見前面的文章。
定義IRepositoryContext接口的主要目的是:因為我們采用的持久化機制是EF,EF是通過DBContext來管理數據操作的事務,一般是針對單實體的。通常我們的業務需要持久化整個聚合的多個實體或通過領域服務或應用服務持久化多個聚合,多個實體或聚合在業務上需要保持一致性,為了達到這個目的,我們引入了工作單元模式與定義了倉儲上下文,通過倉儲上下文來管理操作的多個實體或多個聚合中的實體,然后通過工作單元模式統一提交來保證事務,從而保證業務的一致性。
using System; using System.Collections.Generic; using System.Linq.Expressions; using Order.Domain.Aggreate; namespace Order.Domain.Repository { public interface IRepository<TAggreateRoot> where TAggreateRoot:class,IAggreateRoot { #region 創建對象 void Create(TAggreateRoot aggreateroot); #endregion #region 重建對象 TAggreateRoot GetbyId(Guid id); List<TAggreateRoot> GetbyCondition(Expression<Func<TAggreateRoot, bool>> condition); #endregion #region 更新對象 void Update(TAggreateRoot aggreateroot); #endregion #region 銷毀對象 void Remove(TAggreateRoot aggreateroot); void RemoveById(Guid id); #endregion } }
namespace Order.Domain.Repository { public interface IUnitOfWork { bool Committed { get; } void Commit(); void RollBack(); } }
using Order.Domain.Aggreate; using System; namespace Order.Domain.Repository { public interface IRepositoryContext:IUnitOfWork,IDisposable { Guid ContextId { get; } /// <summary> /// 在事務上下文中標記聚合根為創建狀態 /// </summary> /// <typeparam name="TAggreateRoot"></typeparam> /// <param name="aggreateroot"></param> void RegisterCreate<TAggreateRoot>(TAggreateRoot aggreateroot) where TAggreateRoot:class,IAggreateRoot; /// <summary> /// 在事務上下文中標記聚合根為更改狀態 /// </summary> /// <typeparam name="TAggreateRoot"></typeparam> /// <param name="aggreateroot"></param> void RegisterUpdate<TAggreateRoot>(TAggreateRoot aggreateroot) where TAggreateRoot : class, IAggreateRoot; /// <summary> /// 在事務上下文中標記聚合根為銷毀狀態 /// </summary> /// <typeparam name="TAggreateRoot"></typeparam> /// <param name="aggreateroot"></param> void RegisterRemove<TAggreateRoot>(TAggreateRoot aggreateroot) where TAggreateRoot : class, IAggreateRoot; } }
歡迎加入QQ討論群:309287205
