Skip to content

atharkes/generics

Repository files navigation

Generics

Generic solutions to common problems.

Generics.Infrastructure.EntityFramework

Generic repository implementations for entity framework including the Generics.Specifications specification pattern.

Sample: Dependency Injection

services.AddScoped(typeof(IRepository<>), typeof(GenericDbContextRepository<>));
services.AddScoped<IRepository, DbContextRepository>();

Sample: Repository Usage

var employeeName = await _repository.SingleOrDefault(new EmployeeNameByIdSpecification(employeeId));

Generics.Specifications

Powerful and immutable specification pattern.

Sample: Specification Creation

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;
}

Generics.Specifications.EntityFramework

Apply the specification pattern in an entity framework repository.

Sample: Repository Implementation

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);

Credits

About

Generic solutions to specific problems

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages