Unit of work

Recently, I often meet with interesting pattern(design pattern) – unit of work. I liked this pattern quickly and I get used to implementing it in my programs. This is why I considered to share few words about this pattern and my implementation of it.

Unit of Work is great pattern intended to create an abstraction layer between the DAL(data access layer) and BLL(bussiness logic layer). Simply, Unit of Work is container for repositories, where Repository(next pattern) is provider of set of operations on single entity(usually CRUD operations but it can be extend). Thanks for its abstracition we can write program independent from DAL(I mean from concrete implementation of access to DB), so we can use next great pattern – Dependency Injection. More, Unit of Work can facilitate writing unit tests or use TDD.

For more information about UoW I strongly recommend below article(above image comes from it):


When I was writing UoW second time in my application I thought that I should create reusable library – and I created. My implementation of UoW is based on Entity Framework(for now). Some people can say now – what for? If Entity Framework isn’t Unit of Work on its own?

Entity Framework can resamble Unit of Work – DbContext as UoW and DbSet as Repository. But Entity Framework classes are concrete implementation – there’s lack of abstraction which is more important in UoW – I think.

In my library I decided to hide Repositories against client. Thanks for this methods responsible for access to DB are very simple e.g. to insert entity of type Employee in DB we only write it: UoW.Insert<Employee>(myEmployee). Important part of my implementation is also take care of two important principles connected to access to DB(open connection as late as possible and close as soon as possible). We wrtie UoW.Query(() => …and here we call one or few methods from UoW) -> and UoW will open connection by first method in Query and close after last method in query – additionaly every methods are involved by transaction(cause SaveChanges from DbContext use transacion).

So, at last word I encourage to test and use my library. It’s published as open source on codeplex here:



This entry was posted in .NET programming. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s