| 類別 | 內容 | 所屬層 |
| 應用邏輯 | 用例流程、交易邊界、DTO 轉換、授權 | 應用層 / 服務層 |
| 領域邏輯 | 業務規則、不變條件、實體行為、領域事件 | 領域層 (核心) |
三、標準層次定義
- 表示層 (UI):領域無關,處理 HTTP、ViewModel、驗證、轉向。
- 服務層 / 應用層:應用邏輯,協調領域物件完成用例。
- 領域層 / 業務邏輯層:領域邏輯,實體、值物件、領域服務、規則引擎。
- 共享層:通用工具、擴充方法、基礎 DTO、常數、介面定義。
- 實現層 / 基礎設施層:介面具體實作 (EF、Dapper、MQ、Email、File、Logging)。
四、DDD 分層演進史
1. 原始 DDD (Eric Evans 2003)
UI → Application → Domain ← Infrastructure (Repository 實作在這裡)
問題:Infrastructure 參考 Domain 導致雙向依賴 (命名空間層面)
2. 改良 DDD (分離共享/實現)
UI → Application → Domain
↑ ↓
Shared Kernel Infrastructure (Shared + Impl)
優點:形式上領域為核心;缺點:共享/實現未徹底分離
3. 最新 DDD / 洋蔥架構 / 整潔架構
┌─────────────────────┐
│ Infrastructure │ ← 實現層 (外層)
│ (EF, MQ, Clock) │
└──────────┬──────────┘
│ 實作介面
┌──────────▼──────────┐
│ Application │ ← 應用服務
└──────────┬──────────┘
│ 使用
┌──────────▼──────────┐
│ Domain │ ← 核心 (最內層)
│ (Entities, Rules) │
└─────────────────────┘
- **依賴倒置徹底化**:Domain 定義介面,Infrastructure 實作,Application 依賴 Domain 介面。
- **同心圓依賴**:外層依賴內層,內層零依賴。
- **共享層獨立**:`SharedKernel` 僅含跨邊界的介面/DTO/例外,無實作。
五、架構演進趨勢
| 趨勢 | 說明 |
業務邏輯核心化領域模型豐富化、貧血模型 → 充血模型、行為封裝在實體中 |
技術依賴外移所有具體技術 (ORM、MQ、Clock、File) 統一到 Infrastructure,Domain 純淨 |
方案內低耦合優於方案間復用單一解決方案內專案分層清晰,跨方案共用透過 NuGet 套件 |
共享/實現分離常態化Infrastructure 拆為 `Infrastructure.Shared` (介面/DTO) + `Infrastructure.Impl` (實作) |
架構風格標準化Clean Architecture、Onion Architecture、Hexagonal Architecture 互通有無 |
六、.NET 專案實際建議
// 專案引用方向 (箭頭 = 依賴)
MyApp.WebAPI → MyApp.Application, MyApp.Infrastructure (DI 註冊)
MyApp.Application → MyApp.Domain, MyApp.Infrastructure.Shared
MyApp.Domain → (無)
MyApp.Infrastructure.Impl → MyApp.Domain, MyApp.Infrastructure.Shared
MyApp.Infrastructure.Shared → MyApp.Domain (介面/DTO)
MyApp.Tests → MyApp.Domain, MyApp.Application, MyApp.WebAPI
結語: 架構服務於業務演進。小專案用三層,大專案用 DDD/Clean,核心永遠是**保護領域邏輯不被技術細節污染**,並讓變化發生在外層。
copyright ©
萬盛學電腦網 all rights reserved