I would like to implement simple IGenericRepository and IUnitOfWork interfaces in my application but I'm not sure whats the best way to do it.
As far as I could understand, UnitOfWork should be used for writing, while Repository should be used for reading. I have encountered one architecture and I really like it, but I only found interfaces and not the implementations, and I'm not sure how should I implement those.
public interface IGenericRepository : IDisposable
{
IUnitOfWork CreateUnitOfWork();
T FirstOrDefault<T>(Expression<Func<T, bool>> predicate) where T : class, IBaseEntity;
IQueryable<T> Get<T>(Expression<Func<T, bool>> predicate = null, Func<IQueryable<T>, IOrderedQueryable<T>> sorter = null, params string[] includeProperties) where T : class, IBaseEntity;
IQueryable<T> GetAll<T>() where T : class, IBaseEntity;
IDbContext GetDbContext();
}
public interface IUnitOfWork : IDisposable
{
int Commit();
bool Delete<T>(T entity) where T : class, IBaseEntity;
int DeleteItems<T>(IList<T> entities) where T : class, IBaseEntity;
bool Insert<T>(T entity) where T : class, IBaseEntity;
int InsertItems<T>(IList<T> entities) where T : class, IBaseEntity;
bool Update<T>(T entity) where T : class, IBaseEntity;
int UpdateItems<T>(IList<T> entities) where T : class, IBaseEntity;
}
I'm not sure how should those work. Should I use IDbContextFactory within repository to share DbContext between Repository and UnitOfWork or they should have separate DbContexts? If I implement UnitOfWork for write and Repository for read, should there be UnitOfWorks DbContext for write and Repositorys DbContext for read or they should share same DbContext?
I would really appreciate good explanation of how DbContext and UnitOfWork/Repository should work.
Those would be implemented in service in such way:
public CustomerService(IGenericRepository repository)
{
this.repository = repository;
this.context = this.repository.GetDbContext();
}
public void UpdateCustomer(Customer customer)
{
var uow = this.repository.CreateUnitOfWork();
uow.AddForSave(customer);
uow.Commit();
}
public List<Customer> GetAll()
{
return this.repository.GetAll<Customer>();
}
Any help, explanation about DbContext and UoW/Repository relation, or good tutorial similar to this implementation would help.
Regards.
UnitOfWork should be used for writing, while Repository should be used for reading
I've never heard of that – Jonesopolis