17
2015/09/11 Repository Pattern

Introduction the Repository Pattern

Embed Size (px)

Citation preview

Page 1: Introduction the Repository Pattern

2015/09/11

Repository Pattern

Page 2: Introduction the Repository Pattern

2

3-tier Architecture

Database

Entity Framework

Business Service

Controller

Data AccessLayer

ServiceLayer

PresentationLayer

Page 3: Introduction the Repository Pattern

3

如果程式已完成 90% 時,高層忽然下令不准用 Entity Framework ,要改用 Nhibernate 。( 上線時間不變 )

Challenge

Page 4: Introduction the Repository Pattern

4

• 爆肝加班• 落人幫忙• 擺爛• 離職

Solution

Page 5: Introduction the Repository Pattern

5

Repository Pattern

圖片來源: Implementing the Repository and Unit of Work Patterns in an ASP.NET MVC Application

Page 6: Introduction the Repository Pattern

6

DefinitionMartin Fowler 定義: Repository 是領域層與資料對應層之間的媒介,如同存在記憶體中的物件集合。用戶端會建構查詢規格( query specification ),並傳遞給 Repository 以執行特定的資料操作 ..... 概念上, Repository 將資料與其相關操作封裝成物件集合,以便用貼近物件導向的方式來存取資料。

Martin Fowler ,軟體工程師,也是一個軟體開發方面的著作者和國際知名演說家,專注於物件導向分析與設計,統一建模語言,領域建模,以及敏捷軟體開發方法,包括極限編程。

Page 7: Introduction the Repository Pattern

7

Definition

將 DAL 以 Repository 封裝,外部透過 Repository 來取資料,無須理會資料來源的種類。

Page 8: Introduction the Repository Pattern

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

Page 9: Introduction the Repository Pattern

9

定義 Repository 的 interface

Page 10: Introduction the Repository Pattern

10

實作 Repository interface

Page 11: Introduction the Repository Pattern

11

實作 Repository interface

Page 12: Introduction the Repository Pattern

12

使用 Repository

Page 13: Introduction the Repository Pattern

13

使用 Repository

Page 14: Introduction the Repository Pattern

14

使用 Repository

Page 15: Introduction the Repository Pattern

15

抽換 Repository

Page 16: Introduction the Repository Pattern

16

使用 Repository 的理由• 利於單元測試• 避免上層服務直接依賴 Entity Framework ,以便抽換成其他 DAL 技術• 可搭配 Unit of Works 來進行交易

(Transaction)

Page 17: Introduction the Repository Pattern

17

不使用 Repository 的理由• 利於單元測試

− 沒有 Repository 還是可以做 unit test ,對象改為商業邏輯層 ( 前提是要具備 N-tier 架構 )• 避免上層服務直接依賴 Entity Framework ,以便抽換成其他 DAL 技術

− 實務上更換 DAL 、 DB 的機會不大• 可搭配 Unit of Works 來進行交易

(Transaction)− Entity Framework 已提供類似功能