承接上篇「問題導向設計」,本文落實三層式架構(UI、BLL、DAL)於 Visual Studio 方案中,並闡述各層職責邊界與溝通協定,為後續模組開發奠定基石。
EnterpriseSolution.sln
├── Enterprise.UI.Web // ASP.NET WebForm / MVC 專案
├── Enterprise.UI.Controls // 自訂伺服器控制項、使用者控制項
├── Enterprise.BLL // 業務邏輯層(核心領域模型、服務、驗證規則)
├── Enterprise.DAL // 資料存取層(Repository、Entity、Stored Procedure 呼叫)
├── Enterprise.Common // 共用工具、擴充方法、常數、例外定義
└── Enterprise.Tests // 單元測試、整合測試專案

IUserService)呼叫 BLL,降低耦合設計原則:封裝易變更的業務規則
public class UserService : IUserService
{
private readonly IUserRepository _repo;
public UserService(IUserRepository repo) { _repo = repo; }
public void CreateUser(string userName)
{
// 唯一性驗證集中於此,呼叫端無需重複
if (_repo.Exists(userName))
throw new BusinessException("使用者名稱已存在");
var user = new User { Name = userName, CreatedAt = DateTime.Now };
_repo.Add(user);
}
public void BatchImportUsers(IEnumerable names)
{
// 批次匯入複用同一驗證邏輯
foreach (var name in names)
CreateUser(name); // 交易邊界由上層控制
}
}
IUserRepository 介面,實作可替換UI --> BLL (介面) <-- DAL (實作)
^
| 參考 Common
| 誤區 | 對策 |
|---|---|
| BLL 淪為 DAL 的透傳封裝 | BLL 必須包含業務決策(驗證、流程控制、領域事件),非單純 CRUD 轉呼 |
| UI 直接引用 DAL 或 Entity Framework Context | 嚴禁跨層引用;使用 DTO/ViewModel 傳遞資料 |
| 業務規則分散在 UI 事件、Stored Procedure、BLL | 建立業務規則目錄,強制集中於 BLL 領域服務 |
後續將示範:
三層架構非銀彈,但若能嚴守職責邊界、善用介面隔離,即能打造可維護、可測試、可演進的企業級系統。