Search code examples
asp.net-mvcdesign-patternsninjectrepository-patternunit-of-work

Injecting UnitOfWork in a Using block


I worked on a UnitOfWork / Repository / MVC application. Now that this is working all great, I want to decouple the UnitOfWork from the controllers. One way of doing it is to inject the dependency with Ninject (or other) in the controller's contructor. However, this means the UnitOfWork will be instanciated at the same time as the controller.

The way I want to use my UnitOfWork is with Using blocks like so:

using(var unitOfWork = new IUnitOfWork)
{
    return unitOfWork.GetRepository<IEmployeesRepository>().GetAllEmployees();
}

Obviously you cant instance a interface, you have instance an implementation which is injected with a dependency injector, but how can I inject it in a using clause?

I saw Property injection and Method injection but I am unsure of how I could use those to acheive my goal.


Solution

  • Use a factory which you register in the container:

    public class UserController : Controller
    {
        IUnitOfWorkFactory _factory;
    
        public UserController(IUnitOfWorkFactory factory)
        {
            _factory = factory;
        }
    
        public ActionResult DoSomething()
        {
            using(var unitOfWork = _factory.Create())
            {
                return unitOfWork.GetRepository<IEmployeesRepository>().GetAllEmployees();
            }
        }
    }
    

    imho it's better to abstract away the UoW handling: http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/