Tutorials Design Patterns in C#
Repository Pattern — Complete Guide
Repository Pattern — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Design Patterns in C# on Toolliyo Academy.
On this page
Design Patterns in C# · Lesson 24 of 69
Repository Pattern
GoF Core ✓ → Enterprise → Cloud & Craft
Enterprise · 2 — App patterns · ~6 min · Module 4: Enterprise Design Patterns
What is this?
Repository mediates between domain and data mapping — collection-like interface over persistence.
Why should you care?
ShopNest OrderService should not embed EF queries in every method if you want tests and storage flexibility.
See it live — copy this example
Paste into a C# console or class library project and run dotnet run.
public interface IOrderRepository
{
Task<Order?> GetAsync(Guid id);
Task AddAsync(Order order);
}
public sealed class Order
{
public Guid Id { get; init; } = Guid.NewGuid();
public string Sku { get; init; } = "";
}
public sealed class InMemoryOrderRepository : IOrderRepository
{
private readonly Dictionary<Guid, Order> _db = new();
public Task<Order?> GetAsync(Guid id) => Task.FromResult(_db.TryGetValue(id, out var o) ? o : null);
public Task AddAsync(Order order) { _db[order.Id] = order; return Task.CompletedTask; }
}
var repo = new InMemoryOrderRepository();
var order = new Order { Sku = "HD-100" };
await repo.AddAsync(order);
Console.WriteLine((await repo.GetAsync(order.Id))!.Sku);
Run Example »
Edit the code below and click Run to see the result in Toolliyo’s live editor.
What happened?
- IOrderRepository hides storage.
- In-memory impl powers tests; EF impl used in prod.
- Avoid generic repositories that leak IQueryable everywhere.
Practice next
- Add and get an order.
- Write a fake for a unit test.
- Add FindBySkuAsync on the interface.
- Throw if duplicate id on Add.
- List all orders method.
Remember
Collection-like persistence port. Swap impls for tests. Model aggregates.
ShopNest order repository
Handlers depend on IOrderRepository.
Outcome: EF changes stay in infrastructure.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!