SOLID & Design Patterns Interview Question #19
What is a Generic Repository and when can it become problematic?
SOLID Principles, Design Fundamentals, Repository, Factory, Strategy & Decorator Junior Beginner
Quick Interview Answer
A Generic Repository defines reusable CRUD operations for many entity types, often through an interface such as IRepository<T>. It can reduce repeated basic code in applications with simple persistence needs.
Detailed Explanation
A Generic Repository defines reusable CRUD operations for many entity types, often through an interface such as IRepository<T>. It can reduce repeated basic code in applications with simple persistence needs.
It becomes problematic when different aggregates require different query behavior, includes, transactions, or invariants. A very generic abstraction may either leak IQueryable everywhere or grow many special-case methods, reducing the value of the abstraction.
Code Example
public interface IRepository<T>
{
Task<T?> GetByIdAsync(int id);
Task AddAsync(T entity);
void Remove(T entity);
}