Repository 模式 (Repository Pattern)

Repository 模式的好處

在軟體分層那篇文章中,資料存取層的實作便是 Repository 模式的體現,有效的將資料存取隔離於商業邏輯之外,當要抽換資料來源時,無須改動展示層與商業邏輯層(前提是 Repoistory 約定的介面沒有變動)。

專用型 IRepository 與 泛型 IRepository

我們先定義兩種應用的模式

  • 專用型 Repository:一個 interface 實作 一個 Repository

public interface IBlogRepository
{
    // ....
}

public class BlogRepository : IBlogRepository
{
    // ....
}

public interface IPostRepository
{
    // ....
}

public class PostRepository : IPostRepository
{
    // ....
}
  • 泛型 Repository:一個 interface 實作 一個 Repository,透過不同的 TEntity 來操作不同的資料表。

當 Repository 有不同的介面方法的時候,專用型 Repository 能提供最大的彈性。

當 Repoitory 有固定的 CRUD 的介面方法,泛型 Repository 可以有效的減少重複的程式碼。

專用型 Repository

DBContext

EFCore 使用指定產生出 DBContext 如下

Respository 介面

Repository 實作

Repository 介面與 Service 使用都不需修改,只需修改 Repository 實作的部分 (有沒有開始感受到分層抽離,依賴建介面的好處)

Service 的應用

注入 IBlogRepository 就可以使用。

注入設定

泛型 Repository 模式

泛型 IRepository

泛型 IRepository 實作

注入設定

Repository Pattern & Unit Of Work

職責分離 首先先調整 UnitOfWork 的介面與實作

再來修改 Repository 的實作

再來是 Service 的修改

整個專案的架構圖如下 UnitOfWork

文章連結

Last updated