Upload
bill-lin
View
576
Download
6
Embed Size (px)
Citation preview
2015/09/11
Repository Pattern
2
3-tier Architecture
Database
Entity Framework
Business Service
Controller
Data AccessLayer
ServiceLayer
PresentationLayer
3
如果程式已完成 90% 時,高層忽然下令不准用 Entity Framework ,要改用 Nhibernate 。( 上線時間不變 )
Challenge
4
• 爆肝加班• 落人幫忙• 擺爛• 離職
Solution
5
Repository Pattern
圖片來源: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application
6
DefinitionMartin Fowler 定義: Repository 是領域層與資料對應層之間的媒介,如同存在記憶體中的物件集合。用戶端會建構查詢規格( query specification ),並傳遞給 Repository 以執行特定的資料操作 ..... 概念上, Repository 將資料與其相關操作封裝成物件集合,以便用貼近物件導向的方式來存取資料。
Martin Fowler ,軟體工程師,也是一個軟體開發方面的著作者和國際知名演說家,專注於物件導向分析與設計,統一建模語言,領域建模,以及敏捷軟體開發方法,包括極限編程。
7
Definition
將 DAL 以 Repository 封裝,外部透過 Repository 來取資料,無須理會資料來源的種類。
8
SQL Server
程式架構
Controllers
PresentationLayer
Views View Models
DomainModel
EF DbContext
EF DbSet<T>
Entity Framework
HTMLJavaScript
AJAX
UserInterface
Repositories
BizEntities
EF Entities
Business ServiceBusinessLayer Business Utilities / Helpers
Web API
Common
Utilities
9
定義 Repository 的 interface
10
實作 Repository interface
11
實作 Repository interface
12
使用 Repository
13
使用 Repository
14
使用 Repository
15
抽換 Repository
16
使用 Repository 的理由• 利於單元測試• 避免上層服務直接依賴 Entity Framework ,以便抽換成其他 DAL 技術• 可搭配 Unit of Works 來進行交易
(Transaction)
17
不使用 Repository 的理由• 利於單元測試
− 沒有 Repository 還是可以做 unit test ,對象改為商業邏輯層 ( 前提是要具備 N-tier 架構 )• 避免上層服務直接依賴 Entity Framework ,以便抽換成其他 DAL 技術
− 實務上更換 DAL 、 DB 的機會不大• 可搭配 Unit of Works 來進行交易
(Transaction)− Entity Framework 已提供類似功能