C# Interview Question #154

What is the Repository Pattern?

Design Patterns & Production Architecture Senior Advanced

Quick Interview Answer

The Repository Pattern provides an abstraction over data access and presents collection-like operations for domain or application code.

Detailed Explanation

The Repository Pattern provides an abstraction over data access and presents collection-like operations for domain or application code.

It can centralize complex persistence queries and help isolate data-access concerns. However, Entity Framework Core's DbContext and DbSet already implement repository/unit-of-work-like responsibilities.

Therefore, a generic repository over EF Core can sometimes add unnecessary abstraction or hide useful EF Core features. Repositories are most valuable when they express meaningful domain-specific queries or provide an intentional persistence boundary.

Code Example

public interface IProductRepository
{
    Task<Product?> GetByIdAsync(
        int id,
        CancellationToken cancellationToken);

    Task<IReadOnlyList<Product>> GetFeaturedAsync(
        CancellationToken cancellationToken);
}