my Controllers usually consume one or two Services. In turn, I inject a same Unit of Work to these Services to use the same Context. That is:
public class TestController : Controller
{
private UnitOfWork _unitOfWork;
private Service1 _service1;
private Service2 _service2;
public TestControler()
{
_unitOfWork = new UnitOfWork();
// here I inject the unit of work to the services.
_service1 = new Service1(_unitOfWork);
_service2 = new Service2(_unitOfWork);
}
}
My questions:
- How should I implement unit testing? Should I inject the unit of work
only, or unit of work and services too? - How can I dispose the objects? Should I dispose the unit of work or
the services (which in turn dispose the unit of work)?
1.) all dependencies should be injected, so anything you are newing up in the controller, which for you would be your unit of work and two services. this will make testing work properly, as you’ll be able to mock all dependencies. actually, looking at it more, you shouldn’t be injecting the unitofwork class, as it is only a dependency of the services.
2.) your services shouldn’t need disposing if the unit of work object is actually handling all the work. my suggestion would be to implement idisposable on the UnitOfWork class and put it in a using()