Unit of work/repository pattern with dependency injection advice

by Andrew Stephens   Last Updated October 17, 2017 19:05 PM

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!



Answers 2


What you're describing is a really common pattern where instead of injecting the object of interest you want to inject an object that can create instances of the object of interest. You might call it a factory. If you are using Autofac it is baked in by simply injecting Func<T> (to create instances of T). I'm pretty sure Castle Windsor has this same feature.

You may need to consider the boundaries of your unit of work further. Your question implies that a unit of work falls within the boundaries of, say, SaveCustomer but ask yourself what if I reuse that method within a larger unit of work. What are the boundaries of your unit of work then, and does your injection strategy and unit of work implementation handle that correctly.

quentin-starin
quentin-starin
January 11, 2013 21:01 PM

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.

jgauffin
jgauffin
January 11, 2013 21:24 PM

Related Questions


Relationship between Repository and Unit of Work

Updated October 17, 2017 12:05 PM