liveBook · Manning

Repository pattern

As explained in Unit Testing Principles, Practices, and Patterns

A repository is an abstraction that provides access to and modification of persisted data for a particular domain object or aggregate.

A repository is a short-lived abstraction for accessing and modifying persisted data belonging to a domain object or aggregate. It separates database interaction from the transaction that decides whether a business operation commits or rolls back. section 10.2

Use repositories with these boundaries:

  • Create focused repositories such as UserRepository and CompanyRepository rather than one general Database class. section 10.2
  • Let repositories operate on the current transaction; keep transaction lifetime aligned with the whole business operation. section 10.2
  • Prefer integration tests for repository behavior instead of isolated repository tests when the repository has little complexity and mainly communicates with the database. section 10.5
  • Extract any meaningful repository algorithm into a self-contained unit that can be tested independently. section 10.5

Refactoring a user update

A controller first loads a user and company, validates the email change, and saves both objects. Replacing direct Database calls with UserRepository and CompanyRepository keeps those data operations inside one Transaction, so a failure cannot leave the company updated while the user remains unchanged. With Entity Framework, both repositories can share a CrmContext; an integration test can arrange through those repositories and call SaveChanges once.

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines responsibilities, lifespans, transaction enlistment, testing trade-offs, and a repository refactoring, but not database internals.
Examples
Uses UserRepository, CompanyRepository, CrmContext, a user email change, and an integration test sharing context.
What it assumes
Assumes domain objects, database access, business operations, transactions, and integration tests; teaches repository boundaries from their interaction.
What you can do after
Apply it via focused repositories and shared transactions, then evaluate repository tests by maintenance cost and regression value.
How it connects
Connects repositories with transactions, unit of work, integration testing, domain modeling, and object-relational mapping.

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 Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.