I'm trying to implement the unit of work pattern with dependency injection / inversion of control and entity framework version 6.1.1 Code First, in an asp.net-mvc project.
public interface IGenericRepository<T> : where T : class
{
IQueryable<T> AsQueryable();
IEnumerable<T> GetAll();
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
T Single(Expression<Func<T, bool>> predicate);
T SingleOrDefault(Expression<Func<T, bool>> predicate);
T First(Expression<Func<T, bool>> predicate);
T GetById(int id);
void Add(T entity);
void Delete(T entity);
void Attach(T entity);
}
public interface IUnitOfWork : IDisposable
{
IGenericRepository<Order> OrderRepository { get; }
IGenericRepository<Customer> CustomerRepository { get; }
IGenericRepository<Employee> EmployeeRepository { get; }
void Commit();
}
public class EfUnitOfWork : DbContext, IUnitOfWork
{
private readonly EfGenericRepository<Order> _OrderRepo;
private readonly EfGenericRepository<Customer> _customerRepo;
private readonly EfGenericRepository<Employee> _employeeRepo;
public DbSet<Order> Orders { get; set; }
public DbSet<Customer> Customers { get; set; }
public DbSet<Employee> Employees { get; set; }
public EfUnitOfWork()
{
_orderRepo = new EfGenericRepository<Order>(Orders);
_customerRepo = new EfGenericRepository<Customer>(Customers);
_employeeRepo = new EfGenericRepository<Employee>(Employees);
}
#region IUnitOfWork Implementation
public IGenericRepository<Order> OrderRepository
{
get { return _orderRepo; }
}
public IGenericRepository<Customer> CustomerRepository
{
get { return _customerRepo; }
}
public IGenericRepository<Employee> EmployeeRepository
{
get { return _employeeRepo; }
}
public void Commit()
{
this.SaveChanges();
}
#endregion
}
public class EfGenericRepository<T> : IGenericRepository<T>
where T : class
{
private readonly DbSet<T>_dbSet;
public EfGenericRepository(DbSet<T> dbSet)
{
_dbSet = dbSet;
}
#region IGenericRepository<T> implementation
public virtual IQueryable<T> AsQueryable()
{
return _dbSet.AsQueryable();
}
public IEnumerable<T> GetAll()
{
return _dbSet;
}
public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return _dbSet.Where(predicate);
}
// And so on ...
#endregion
}
And this is how I'm using it in a controller:
public HomeController(IUnitOfWork unitOfWork) { ..... }
But I've read that EF6 already has Unit of Work out of the box. How would that fit in this picture?
Also, with which dependency injector should I go with?
DbSet<T>
is already a repository. \$\endgroup\$