What is the Repository pattern in C#?
Answer
The Repository pattern abstracts data access logic behind an interface, decoupling the domain layer from data persistence concerns. The repository acts as a collection-like interface for accessing domain objects. Example: public interface IUserRepository { Task<User> GetByIdAsync(int id); Task<IEnumerable<User>> GetAllAsync(); Task AddAsync(User user); Task UpdateAsync(User user); Task DeleteAsync(int id); }. Implementation: public class EfUserRepository : IUserRepository { private readonly AppDbContext _ctx; ... }. Benefits: (1) Testability — inject a mock repository in unit tests. (2) Swap data sources without changing domain logic. (3) Centralized query logic. Debate: EF Core's DbContext is itself a Unit of Work + Repository, making an additional repository layer sometimes redundant (the "generic repository antipattern"). Use repositories when: testing requires it, data source might change, or query complexity benefits from centralization. Keep repositories thin — business logic belongs in domain/service layers.
Previous
What is the Observer pattern and how is it implemented in C#?
Next
What is the CQRS pattern in C#?
More C# / .NET Questions
View all →- Intermediate What is ASP.NET Core and how does it differ from ASP.NET Framework?
- Intermediate What is middleware in ASP.NET Core?
- Intermediate What is dependency injection in ASP.NET Core?
- Intermediate What is Entity Framework Core?
- Intermediate What is the difference between eager, lazy, and explicit loading in EF Core?