Skip to content

Repository Pattern Usage

Wendy Yao edited this page Mar 15, 2020 · 3 revisions

The repository pattern as defined by Martin Fowler:

A Repository mediates between the domain and data mapping layers, acting like an in-memory domain object collection. Client objects construct query specifications declaratively and submit them to Repository for satisfaction. Objects can be added to and removed from the Repository, as they can from a simple collection of objects, and the mapping code encapsulated by the Repository will carry out the appropriate operations behind the scenes. Conceptually, a Repository encapsulates the set of objects persisted in a data store and the operations performed over them, providing a more object-oriented view of the persistence layer. Repository also supports the objective of achieving a clean separation and one-way dependency between the domain and data mapping layers.

Benefits:

  • Your business logic can be unit tested without data-access logic (through DI)
  • The database access code can be reused (EFRepository)
  • Provides abstraction layer between controller and database context

Sequence of calls:

  • Controller -> Repository -> EF Core -> SQL Server

Architecture:

We have a repository interface so if we plan to have other ORM's besides EF Core, it contains all the base CRUD operations

image

We have an abstract class called EfRepository that contains all base logic for accessing the database, other repositories can inherit this class to override its functionality.

image

An abstract BaseController is created so that future controllers will not have to have instantiate the repositories. It will also provide base CRUD operations to every entity that has a relevant controller. image

Repositories are injected inside the specific entity controller, which make the calls to the database. This is to avoid the controller having data-access logic.

image

Finally, the repositories have to be added to the scope in the StartUp for the DI to work.

image

Clone this wiki locally