Skip to content
Tutorials Center
My learning

Topics

Lesson 151 of 182 ยท Data Access

Repositories, Unit of Work and Clean Architecture

Understand the repository and unit of work patterns in C#, what EF Core already gives you, specifications, testing with fakes, and Clean Architecture dependencies, with runnable code.

Sooner or later every codebase asks the same question: where does the database code live, and how do I keep the rest of the program from depending on it? Two classic answers are the repository pattern (a collection-like object that hides how entities are stored) and the unit of work pattern (a boundary that saves a group of changes together or not at all). They are usually taught together, often with an IRepository<T> interface on every entity.

In modern .NET these patterns are controversial. Entity Framework Core's DbSet<T> already is a repository and DbContext already is a unit of work, so wrapping them can add code without adding value. This lesson explains what the patterns are, builds them from scratch in memory so you can run them, shows when they genuinely help (testing, boundaries, query reuse) and when they are ceremony, and ties them into Clean Architecture. For the underlying tools see Entity Framework Core and Data Access in .NET.

The repository pattern

A repository presents stored entities as if they were an in-memory collection: you add, remove and find objects, and the details (SQL, files, web service calls) stay behind an interface. The point is that the caller states what it needs in domain terms ("get the customer with this email") without knowing how that is fetched.

The interface belongs to the code that uses it (the application or domain layer), and the implementation belongs to the infrastructure. That inversion is what lets you swap SQL for a fake in a test:

C#
public interface ICustomerRepository
{
    Task<Customer?> FindByEmailAsync(string email, CancellationToken cancellationToken = default);
    Task<IReadOnlyList<Customer>> ListInCityAsync(string city, CancellationToken cancellationToken = default);
    void Add(Customer customer);
}

Notice what is not here: no IQueryable, no SQL, no DbContext. Methods are named after questions the application asks, not after table operations. This is a specific repository, one tailored to the use cases. Its opposite is the generic repository IRepository<T> with GetAll(), GetById(), Add(), Delete(). The generic version is easy to write once, but it usually leaks: callers need filters, so it grows an IQueryable<T> or a Func<T, bool>, and then the abstraction hides nothing.

Let's build a generic one first, in memory, so the shape is concrete:

C# A generic in-memory repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Note that Where takes a Func<T, bool>. With a real database that would download every row before filtering, because a delegate cannot become SQL (see expression trees). That is the first reason generic repositories get awkward.

The unit of work pattern

A unit of work tracks the changes you make during one business operation and writes them together, atomically. Placing an order might add an Order, add several OrderLine rows and decrease stock. Either all of that is saved, or none of it. Without a unit of work, a failure halfway leaves the data inconsistent.

The pattern has three parts: the unit of work object exposes repositories, repositories stage changes rather than writing immediately, and a single Commit() applies everything. Let's model it, including an integrity rule (unique emails) that makes the whole commit fail:

C# Unit of work: all or nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The second commit adds Kim and an imposter with Ada's email. The commit fails as a whole, so Kim is not saved either: the store still has two customers. The third block shows the safe default, a unit of work disposed without Commit changes nothing.

In a real application the relationship is: the repository's Add marks an entity for insertion, and Commit (SaveChanges) turns all marks into SQL in one database transaction. Nothing in your code needs to open the transaction by hand.

EF Core already does this

Look at what the pattern contains and what EF Core ships:

Pattern part EF Core
Repository (a collection of entities) DbSet<T> with Add, Remove, Find, LINQ
Unit of work (track, then commit atomically) DbContext change tracker and SaveChanges()
Identity map (same row, same object) the context's identity resolution

So IRepository<T> wrapping DbSet<T> mostly renames methods. It also makes things worse in common ways: it hides Include and projections (hurting performance), forces you to add a method for every query, and tempts you to return IQueryable anyway. That is why many experienced teams say "don't wrap EF Core in a generic repository" and inject the DbContext into application services (or into query handlers) directly.

Reasons to still add a repository or a custom boundary:

  • Testability by isolation when the logic is complex enough to deserve fast unit tests without a database. (EF Core's in-memory and SQLite providers also make real-ish tests easy; see testing fundamentals.)
  • Protecting the domain from infrastructure: the core business code should not reference EF Core types.
  • Aggregates: one repository per aggregate root (such as Order with its lines) that loads and saves the whole group consistently.
  • Several storage technologies behind one interface: SQL for orders, a cache or document store for something else.
  • Reusable, named queries so that "active customers in a city" is defined once.

If none of these apply, you probably do not need the layer.

Specifications instead of leaking IQueryable

If callers must express filters, give them a small object rather than IQueryable. A specification packages a criteria expression (an Expression<Func<T, bool>>) under a name. A SQL-backed repository passes the expression to Where, which translates it, and the in-memory one compiles it:

C# Named, reusable query specifications

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Because the criteria is an expression tree, the same specification works in memory and against a database. The caller says what, the repository decides how.

Testing through the abstraction

The practical payoff of an interface is that business logic can be tested with a fake. Here a small service depends on ICustomerRepository, gets it through dependency injection (DI), and a tiny test harness checks behavior without any database. Our runner has no test framework, so the harness is hand-rolled; see testing fundamentals for the idea.

C# Dependency injection and a fake repository

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

RegistrationService has no idea whether customers live in SQL Server or in a list. That is dependency inversion in practice: the service depends on an abstraction it owns, and the composition root decides the implementation.

Clean Architecture in a nutshell

Clean Architecture (and its relatives: Onion, Hexagonal) arranges code in rings with one rule: dependencies point inward. The core knows nothing about databases, web frameworks or UI.

TEXT
Solution layout (read-only sketch)

Shop.Domain          entities, value objects, domain rules      -> depends on nothing
Shop.Application     use cases, interfaces (ICustomerRepository) -> depends on Domain
Shop.Infrastructure  EF Core DbContext, repository classes       -> depends on Application
Shop.Web             ASP.NET Core endpoints, DI registration     -> depends on all (composition root)
  • Domain holds the model and its invariants (a customer cannot have an empty name).
  • Application holds the use cases ("register customer", "place order") and the interfaces they need from the outside world.
  • Infrastructure implements those interfaces with EF Core, HTTP clients, file storage.
  • Web (or a worker, or a console app) wires everything together at startup, as Program.cs did above with ServiceCollection.

Benefits are real: the core is testable without a database, and replacing a technology touches one project. The cost is also real: more projects, more mapping code and more indirection. For a small CRUD app the layers are overhead. A sensible approach is to start with a single project organized by feature, extract boundaries when a module becomes complex, and add interfaces where you have a reason (a test, a second implementation, a stable seam).

You can enforce "dependencies point inward" with project references: Domain simply has no reference to Infrastructure, so the compiler stops violations. Architecture tests (libraries such as NetArchTest) can check the same rules in a test run; they are a NuGet package, so not available in our runner.

When to use and when to avoid

  • Use a repository for aggregate-oriented domains, when you need to isolate infrastructure, or when the same data comes from different stores. Name methods after use cases.
  • Use a unit of work whenever one operation touches several entities. With EF Core you already have it: call SaveChanges() once at the end of the operation, not in the middle of loops.
  • Avoid generic IRepository<T> over EF Core, repositories that return IQueryable, and one repository per table by reflex.
  • Prefer query objects, specifications or direct DbContext projections for reads, and repositories (if any) for writing aggregates. Splitting reads from writes like this is the core of CQRS thinking.
  • Be careful with transactions across repositories: they must share the same context or connection, which is why the unit of work owns them.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which EF Core types already play the roles of repository and unit of work?

    A DbSet exposes add/remove/find/query over entities, while the DbContext tracks changes and saves them together, which is the unit of work.
  2. 2. Why is a repository method taking Func<T, bool> a problem when backed by a database?

    Only Expression<Func<T, bool>> can be translated to SQL. A plain delegate forces client-side filtering after loading the rows.
  3. 3. In the unit of work demo, why did Kim not get saved when the imposter's email was a duplicate?

    The unit of work validates and applies changes on a copy and swaps it in only if everything succeeds, which is the atomicity a database transaction provides.
  4. 4. In Clean Architecture, where should the ICustomerRepository interface live?

    Dependencies point inward: the inner layer owns the abstraction, and the outer layer implements it. That is dependency inversion.
  5. 5. When is a custom repository over EF Core hardest to justify?

    A repository that only renames DbSet methods adds code and hides features like Include and projection without giving anything back.

Summary

  • A repository hides storage behind a collection-like interface; a unit of work groups changes and commits them atomically.
  • DbSet<T> and DbContext already implement these ideas, so wrapping them needs a reason: isolation, aggregates, multiple stores or named queries.
  • Prefer specific, use-case-named repositories or specifications over generic IRepository<T> and over exposing IQueryable.
  • Interfaces owned by the inner layer plus dependency injection make business logic testable with fakes.
  • Clean Architecture points dependencies inward: Domain, Application, Infrastructure, with the web app as composition root.
  • Start simple, and add layers when complexity earns them.

Next: Working with SQL and NoSQL from C#