Click here to Skip to main content
12,075,066 members (66,216 online)
Click here to Skip to main content
Add your own
alternative version


8 bookmarked

Unit of work sample implementation for ADO.NET

, 10 Jan 2014 LGPL3
Rate this:
Please Sign up or sign in to vote.
This article demonstrates how you can create a Unit Of Work implementation for ADO.NET I’ve got a couple of questions in my “Repository pattern” article about a unit of work implementation. Here is a sample. This is the actual UoW … Continue reading →

This article demonstrates how you can create a Unit Of Work implementation for ADO.NET

I’ve got a couple of questions in my “Repository pattern” article about a unit of work implementation. Here is a sample.

This is the actual UoW factory. Notice that it have no abstraction more than returning IUnitOfWork from the method. No need to create an abstract factory as the actual creation as it’s trivial.

public class UnitOfWorkFactory
	public static IUnitOfWork Create()
		var connection = new SqlConnection(ConfigurationManager.ConnectionStrings("MyDb").ConnectionString);
		return new AdoNetUnitOfWork(connection, true);

The unit of work itself uses the interfaces defined in System.Data to be completely driver independent. That makes it quite easy to switch DB as long as you don’t use anything but the SQL92 standard in your SQL statements.

public class AdoNetUnitOfWork : IUnitOfWork
	public AdoNetUnitOfWork(IDbConnection connection, bool ownsConnection)
		_connection = connection;
		_transaction = connection.BeginTransaction();
	public IDbCommand CreateCommand()
		var command = _connection.CreateCommand();
		command.Transaction = _transaction;
		return command;
	public void SaveChanges()
		if (_transaction == null)
			throw new InvalidOperationException("Transaction have already been commited. Check your transaction handling.");
		_transaction = null;
	public void Dispose()
		if (_transaction != null)
			_transaction = null;
		if (_connection != null && _ownsConnection)
			_connection = null;


using (var uow = UnitOfWorkFactory.Create())
	var repos = new UserRepository(uow);

The above code requires that the repositories break the Liskovs Substitution Principle in theory. But in reality that will never be a problem unless you switch data layer entirely. But in that case the simplest thing is to adjust the UnitOfWorkFactory so that it returns the new implementation.

Hence do something like this in the repository:

public class UserRepository
	private AdoNetUnitOfWork _unitOfWork;
	public UserRepository(IUnitOfWork uow)
		if (uow == null)
			throw new ArgumentNullException("uow");
		_unitOfWork = uow as AdoNetUnitOfWork;
		if (_unitOfWork == null)
			throw new NotSupportedException("Ohh my, change that UnitOfWorkFactory, will you?");
	public User Get(Guid id)
		using (var cmd = _unitOfWork.CreateCommand())
			cmd.CommandText = "SELECT * FROM Users WHERE Id = @id");
			cmd.AddParameter("id", id);
			// uses an extension method which I will demonstrate in a 
			// blog post in a couple of days
			return cmd.FirstOrDefault<User>();

My motivation to now abstract away the implementation in the repositories is that unit tests can never guarantee that the repositories work. Mocking/stubbing/faking will never work as the read database. Hence you need to use integration tests (= use a DB) to be sure that your repositories work as expected.

That’s it.


This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


About the Author

Founder Gauffin Interactive AB
Sweden Sweden
Founder of OneTrueError, a .NET service which captures, analyzes and provide possible solutions for exceptions.

blog | twitter

You may also be interested in...

Comments and Discussions

QuestionHow to use UserRepository class Pin
Tridip Bhattacharjee2-Jan-16 6:35
professionalTridip Bhattacharjee2-Jan-16 6:35 
QuestionNot sure of the point Pin
Jeremy Stafford 122-Oct-15 17:50
memberJeremy Stafford 122-Oct-15 17:50 
AnswerRe: Not sure of the point Pin
jgauffin22-Oct-15 21:40
memberjgauffin22-Oct-15 21:40 
GeneralRe: Not sure of the point Pin
Jeremy Stafford 17-Nov-15 13:08
memberJeremy Stafford 17-Nov-15 13:08 
GeneralMy vote of 3 Pin
Sk8tz15-Jan-14 23:19
memberSk8tz15-Jan-14 23:19 
GeneralRe: My vote of 3 Pin
jgauffin16-Jan-14 0:11
memberjgauffin16-Jan-14 0:11 
SuggestionRe: My vote of 3 Pin
Sk8tz20-Jan-14 6:36
memberSk8tz20-Jan-14 6:36 
QuestionNice one! Pin
Dan Mordechay11-Jan-14 23:36
memberDan Mordechay11-Jan-14 23:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.160208.1 | Last Updated 10 Jan 2014
Article Copyright 2014 by jgauffin
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid