首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

EntityFramework 領域驅動設計實踐(八):倉儲基礎實作——介面定義、EF 實現與依賴注入

     編輯:關於.NET

為何需要倉儲?

直接使用 EF ObjectContext + LINQ to Entities 雖簡單,但導致:

  1. 領域模型緊耦合 EF 技術架構。
  2. 查詢邏輯硬編碼於領域模型(如 where e.Age >= 60),需求變更須改模型。
  3. 難以切換持久化技術。

倉儲模式解耦領域與基礎設施,引入 Specification 模式(以 Func<T, bool> 為輕量規約)解決查詢硬編碼。

倉儲介面定義(領域層)

public interface IRepository<TEntity> where TEntity : EntityObject, IAggregateRoot {
    void Add(TEntity entity);
    TEntity GetByKey(int id);
    IEnumerable<TEntity> FindBySpecification(Func<TEntity, bool> spec);
    void Remove(TEntity entity);
    void Update(TEntity entity);
}

泛型約束限定為聚合根實體。介面置於領域層,不依賴具體實現。

EF 具體實現:EdmRepository

internal class EdmRepository<TEntity> : IRepository<TEntity> where TEntity : EntityObject, IAggregateRoot {
    readonly ObjectContext _ctx;
    readonly string _entitySetName;

    public EdmRepository(ObjectContext ctx) {
        _ctx = ctx;
        var attr = (AggregateRootAttribute)typeof(TEntity)
            .GetCustomAttributes(typeof(AggregateRootAttribute), true)[0];
        _entitySetName = attr.EntitySetName;
    }
    public void Add(TEntity e) => _ctx.AddObject(_entitySetName, e);
    public TEntity GetByKey(int id) {
        var sql = $"SELECT VALUE ent FROM {_entitySetName} AS ent WHERE ent.Id=@id";
        var q = _ctx.CreateQuery<TEntity>(sql, new ObjectParameter("id", id));
        return q.FirstOrDefault() ?? throw new Exception("Not found");
    }
    public void Remove(TEntity e) => _ctx.DeleteObject(e);
    public void Update(TEntity e) { /* TODO */ }
    public IEnumerable<TEntity> FindBySpecification(Func<TEntity, bool> spec) 
        => throw new NotImplementedException(); // 後續用 Specification 替換
}

聚合根以 [AggregateRoot("EntitySetName")] 標記,實現體透過反射讀取 EntitySetName。

依賴注入整合:Castle Windsor

配置 ObjectContext、EdmRepository<Customer>,建構子注入 ObjectContext。測試代碼驗證倉儲操作完全不感知 EF 細節。

架構圖解

倉儲架構圖

下一步

事務處理上下文、可擴展倉儲框架、Specification 完整實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved