Unit of work/repository pattern with dependency injection advice

dependency-injectionrepository-patternunit-of-work

I'm developing a series of repository classes and a UnitOfWork class (plus its IUnitOfWork interface of course). I'm using Castle Windsor, which injects dependencies via constructors.

My business tier has classes such as "CustomerBusinessLogic", with methods like RetrieveCustomer, SaveCustomer, etc. These in turn use the UOW to perform the database operations.

I'm struggling to find how/where the BLL class should get an instance of the UOW. It doesn't feel right injecting it into the ctr, as a unit of work is exactly that – a unit of work! I think an individual method (LoadCustomer, SaveCustomer) should be responsible for instantiating the UOW for the lifetime of its operation. However doing this means resorting to a service locator, which is an anti-pattern.

Suggestions welcome!

Best Answer

I just finished an article today about the repository pattern (with sample implementations).

The thing with most .NET ioc containers is that they support scoping. That is, they can create objects with a limited lifetime. That works very well with HTTP applications since the scope is the same as the lifetime of a HTTP request.

If you use ASP.NET MVC you can combine that with built in features of MVC to trigger the UoW if no errors where detected: http://blog.gauffin.org/2012/06/how-to-handle-transactions-in-asp-net-mvc3/

If you use any other kind of application I usually create a scope by myself (for instance to wrap a command):

using (var scope = MyContainer.CreateChildCointainer())
{
    using (var uow = scope.Resolve<IUnitOfWork>())
    {
        // do something here


        uow.SaveChanges();
    }
}

The thing is that the repositories etc do not have to be aware of the unit of work (if you use databases in .NET). The UoW implementation can make sure that all OR/M or UoW implementation enlists all db commands in the transaction.