Skip to content

Instantly share code, notes, and snippets.

@joshilewis
Created February 1, 2012 09:06
Show Gist options
  • Save joshilewis/1716059 to your computer and use it in GitHub Desktop.
Save joshilewis/1716059 to your computer and use it in GitHub Desktop.
Simple Unit of Work implementation
using System;
namespace ClassLibrary
{
public interface IDependency
{
void SomeMethod();
}
public class MyClass
{
private readonly IDependency dependency;
private readonly Func<IUnitOfWork> StartNewUnitOfWork;
public MyClass(Func<IUnitOfWork> unitOfWorkProvider,
IDependency dependency)
{
this.dependency = dependency;
this.StartNewUnitOfWork = unitOfWorkProvider;
}
public void DoWork()
{
using (var uow = StartNewUnitOfWork())
{
uow.Begin(() => dependency.SomeMethod());
}
}
}
}
using System;
using NUnit.Framework;
using Rhino.Mocks;
namespace ClassLibrary
{
[TestFixture]
public class MyClassTests
{
[Test]
public void TestDoWork()
{
var dependency = MockRepository.GenerateMock<IDependency>();
dependency.Expect(d => d.SomeMethod());
var uow = MockRepository.GenerateMock<IUnitOfWork>();
var uowProvider = MockRepository.GenerateMock<Func<IUnitOfWork>>();
uowProvider.Expect(u => u.Invoke());
var sut = new MyClass(uowProvider, dependency);
sut.DoWork();
uowProvider.VerifyAllExpectations();
uow.VerifyAllExpectations();
}
}
}
using System;
using NHibernate;
using NHibernate.Context;
namespace ClassLibrary
{
public interface IUnitOfWork : IDisposable
{
void Begin();
void Commit();
void RollBack();
void Begin(Action action);
}
//Implementation
public class UnitOfWork : IUnitOfWork
{
private readonly ISessionFactory sessionFactory;
private ISession currentSession;
private ITransaction currentTransaction;
public UnitOfWork(ISessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public void Begin(Action action)
{
try
{
Begin();
action.Invoke();
Commit();
}
catch (Exception ex)
{
RollBack();
throw ex;
}
}
public void Begin()
{
currentSession = sessionFactory.OpenSession();
CurrentSessionContext.Bind(currentSession);
currentTransaction = currentSession.BeginTransaction();
}
public void Commit()
{
currentTransaction.Commit();
CurrentSessionContext.Unbind(sessionFactory);
}
public void RollBack()
{
currentTransaction.Rollback();
CurrentSessionContext.Unbind(sessionFactory);
}
public void Dispose()
{
currentTransaction.Dispose();
currentSession.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment