liveBook · Manning

Repository pattern

As explained in .NET in Action, Second Edition

The repository pattern is an architectural pattern that encapsulates access to and persistence of domain entities through a collection-like interface between the domain model and data-mapping or persistence layers.

A repository separates the domain model from the data layer by presenting persisted objects and operations through a collection-like interface. It can encapsulate mapping and persistence work, and make data-store dependencies easier to replace in tests. When Entity Framework Core already provides enough abstraction, a repository may be unnecessary. section 7.4.1 section 7.4

A repository interface lets application code request operations without depending directly on the data store. In a customer importer, the importer checks for a customer by email, then creates or updates the customer through that interface. Tests can substitute a fake repository instead of setting up a test database. section 7.4.1 section 7.5

Listing 7.19 ICustomerRepository interface
namespace CustomerBatchImporter;
  
public interface ICustomerRepository
{
  Task CreateAsync(                                  #1
    NewCustomerDto customer);                        #2
  
  Task UpdateAsync(
    UpdateCustomerDto customer);
  
  Task<Customer?> GetByEmailAsync(string email);     #3
}
  
public record NewCustomerDto(                        #4
  string Email,
  string Name,
  string License
) { }                                                #5
  
public record UpdateCustomerDto(
  int Id,
  string? NewName,
  string? NewLicense
) { }

The customer repository interface shows the create, update, and lookup operations used by the importer. section 7.4.1

How .NET in Action, Second Edition covers it

How deep it goes
Defines the collection-like role and demonstrates repository interfaces in an importer, without detailing persistence implementation.
Examples
Uses a CSV customer importer and an XKCD comic repository for unit and integration testing.
What you can do after
Apply it via repository interfaces to substitute fake data stores in unit tests without setting up test databases.
How it connects
Connects domain models, data mapping, Entity Framework Core, fakes, and unit testing.

Also explained in

Compare how 9 books explain repository pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.