Generic solutions to common problems.
Generic repository implementations for entity framework including the Generics.Specifications
specification pattern.
services.AddScoped(typeof(IRepository<>), typeof(GenericDbContextRepository<>));
services.AddScoped<IRepository, DbContextRepository>();
var employeeName = await _repository.SingleOrDefault(new EmployeeNameByIdSpecification(employeeId));
Powerful and immutable specification pattern.
Specifications can be made by inheriting from the Specification<T>
or Specification<TBase, TResult>
class.
public class EmployeeNameByIdSpecification : Specification<Employee, string>
{
public uint EmployeeId { get; }
public EmployeeNameByIdSpecification(uint employeeId) : base(query => query
.Where(employee => employee.Id == employeeId)
.Select(employee => employee.Name)
) => EmployeeId = employeeId;
}
Apply the specification pattern in an entity framework repository.
The specification can be applied by using the Apply<T>(this DbSet<T> dbSet, ISpecification<T> specification)
extension method.
public async Task<IEnumerable<TResult>> List<TResult>(ISpecification<T, TResult> specification, CancellationToken cancellationToken = default)
=> await _dbSet.Apply(specification).ToListAsync(cancellationToken);
- Generics.Infrastructure icon: Database icons created by Smashicons - Flaticon
- Generics.Specifications icon: Specification icons created by Freepik - Flaticon