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);
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
The implementations are quite straightforward (I removed all my comments for readability purpose, but do not forget to add yours ;-) )
As you can see, both implementations make use of IDbContext interface. This interface is just for easy testing purpose:
(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:
And all my services inherit from this base service.
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:
Hope this helps!