Repository
Context: Mediate between the domain and data mapping layers using a collection‑like interface for accessing domain objects.
public interface IRepository<T>{ T GetById(int id); IEnumerable<T> GetAll(); void Add(T entity); void Remove(T entity);}
public class InMemoryRepository<T> : IRepository<T>{ private List<T> _data = new(); public T GetById(int id) => _data.FirstOrDefault(e => e.GetHashCode() == id); public IEnumerable<T> GetAll() => _data; public void Add(T entity) => _data.Add(entity); public void Remove(T entity) => _data.Remove(entity);}Real-world usage example
Section titled “Real-world usage example”Data access abstraction: An application uses IRepository<Customer>; the implementation can be Entity Framework, Dapper, or a mock for unit tests. Business logic is decoupled from data source.
Example: In ASP.NET Core, generic IRepository<T> is often used with EF Core’s DbSet<T>. The repository pattern is common in clean architecture / DDD.