I am trying to decouple my unit of work from my services or repository so that I wont have to touch the UoW code whenever I wish to add a new service. How do I do this?
_categoryService = _unitOfWork.Get<ICategoryService>();
so instead of
_unitOfWork.CategoryService.Add(category)
I can just say;
_categoryService.Add(category);
I am trying to decouple my unit of work from my services or
repository so that I won’t have to touch the UoW code whenever I wish
to add a new service
Well, that’s a good start! ;-)
The solution I am presenting is not the one and only possible solution, there are several good ways to implement UoW (Google will help you out). But this should give you the big picture.
First, create 2 interfaces: IUnitOfWork and IRepository
public interface IUnitOfWork : System.IDisposable
{
IRepository<TEntity> GetRepository<TEntity>() where TEntity : class;
void Save();
}
public interface IRepository<T> : IDisposable where T : class
{
void Add(T entity);
void Delete(T entity);
void Update(T entity);
T GetById(long Id);
IEnumerable<T> All();
IEnumerable<T> AllReadOnly();
IEnumerable<T> Find(Expression<Func<T, bool>> predicate);
}
The implementations are quite straightforward (I removed all my comments for readability purpose, but do not forget to add yours ;-) )
public class UnitOfWork<TContext> : IUnitOfWork where TContext : IDbContext, new()
{
private readonly IDbContext _ctx;
private Dictionary<Type, object> _repositories;
private bool _disposed;
public UnitOfWork()
{
_ctx = new TContext();
_repositories = new Dictionary<Type, object>();
_disposed = false;
}
public IRepository<TEntity> GetRepository<TEntity>() where TEntity : class
{
if (_repositories.Keys.Contains(typeof(TEntity)))
return _repositories[typeof(TEntity)] as IRepository<TEntity>;
var repository = new Repository<TEntity>(_ctx);
_repositories.Add(typeof(TEntity), repository);
return repository;
}
public void Save()
{
try
{
_ctx.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
ex.Entries.First().Reload();
}
}
…
}
public class Repository<T> : IRepository<T> where T : class
{
private readonly IDbContext _context;
private readonly IDbSet<T> _dbset;
public Repository(IDbContext context)
{
_context = context;
_dbset = context.Set<T>();
}
public virtual void Add(T entity)
{
_dbset.Add(entity);
}
public virtual void Delete(T entity)
{
var entry = _context.Entry(entity);
entry.State = EntityState.Deleted;
}
public virtual void Update(T entity)
{
var entry = _context.Entry(entity);
_dbset.Attach(entity);
entry.State = EntityState.Modified;
}
public virtual T GetById(long id)
{
return _dbset.Find(id);
}
public virtual IEnumerable<T> All()
{
return _dbset.ToList();
}
public virtual IEnumerable<T> AllReadOnly()
{
return _dbset.AsNoTracking().ToList();
}
public IEnumerable<T> Find(Expression<Func<T, bool>> predicate)
{
return _dbset.Where(predicate);
}
}
As you can see, both implementations make use of IDbContext interface. This interface is just for easy testing purpose:
public interface IDbContext
{
DbSet<T> Set<T>() where T : class;
DbEntityEntry<T> Entry<T>(T entity) where T : class;
int SaveChanges();
void Dispose();
}
(As you can see, I’m using EntityFramework Code First)
Now that the whole plumbing is set up, let’s have a look at how this could be used in a service.
I have a base service that looks like this:
internal class Service<T> where T : class
{
internal Service(Infrastructure.IUnitOfWork uow)
{
_repository = uow.GetRepository<T>();
}
protected Infrastructure.IRepository<T> Repository
{
get { return _repository; }
}
private readonly Infrastructure.IRepository<T> _repository;
}
And all my services inherit from this base service.
internal class CustomerService : Service<Model.Customer>
{
internal CustomerService(Infrastructure.IUnitOfWork uow) : base(uow)
{
}
internal void Add(Model.Customer customer)
{
Repository.Add(customer);
}
internal Model.Customer GetByID(int id)
{
return Repository.Find(c => c.CustomerId == id);
}
}
And that’s it!
Now, if you want to share the same UoW to several services, in a facade method or somewhere else, it could just look like this:
using (var uow = new UnitOfWork<CompanyContext>())
{
var catService = new Services.CategoryService(uow);
var custService = new Services.CustomerService(uow);
var cat = new Model.Category { Name = catName };
catService.Add(dep);
custService.Add(new Model.Customer { Name = custName, Category = cat });
uow.Save();
}
Hope this helps!