Home ยป How to do Generic Repository with Dependency Injection?

How to do Generic Repository with Dependency Injection?

public interface IRepository<T> : IDisposable where T : Entity
{
    T GetById(int id);
}

public abstract class Repository<T> : IRepository<T> where T : Entity
{
    protected readonly SqlDbContext _context = new SqlDbContext();

    public T GetById(int id)
    {
        return _context.Set<T>().Find(id);
    } 
}

public interface IProductRepository : IRepository<Product>
{
    IEnumerable<Product> GetDiscountedProducts();
}

public class ProductRepository : Repository<Product>, IProductRepository
{
    public IEnumerable<Product> GetDiscountedProducts()
    {
        return _context.Set<Product>().Where(x=>x)…
    }         
}

public HomeController(IProductRepository repository)
{
}

public interface IRepository<TEntity> : IDisposable
                 where TEntity : Entity
{   
   TEntity GetById(int id);
   IEnumerable<TEntity> List(IFilterCriteria criteria);
}

public sealed class ProductDiscountFilterCriteria : IFilterCriteria
{
   // …
}

interface IFilterCriteria<TQuery>
{
   TQuery ToQuery();
}

public sealed class ProductDiscountFilterCriteria : IFilterCriteria<DynamicExpression>
{
  public decimal Discount { get; private set; }

  public DynamicExpression ToQuery()
  {
    // build expression for LINQ clause Where(“Discount” > this.Discount)
  }
}

public sealed class ProductDiscountFilterCriteria : IFilterCriteria<string>
{
  public decimal Discount { get; private set; }

  public string ToQuery()
  {
    // simplified
    return “WHERE Discount < ” + this.Discount;
  }
}

var products = productRepository.List<Product>(
                             new DiscountFilterCriteria { Discount = 50 });