SOLID & Design Patterns Interview Question #17

What is the Repository Pattern?

SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner

Quick Interview Answer

The Repository Pattern provides an abstraction over data access and presents collection-like operations for domain or application code. It can centralize query and persistence behavior and reduce direct dependence on storage details.

Detailed Explanation

The Repository Pattern provides an abstraction over data access and presents collection-like operations for domain or application code. It can centralize query and persistence behavior and reduce direct dependence on storage details.

With Entity Framework Core, DbContext already provides repository and unit-of-work-like behavior. Additional repositories are most valuable when they create a meaningful application boundary rather than simply wrapping every DbSet method one-for-one.

Code Example

public interface IProductRepository
{
    Task<Product?> GetByIdAsync(int id);
    Task<IReadOnlyList<Product>> GetActiveAsync();
    Task AddAsync(Product product);
}