Skip to content

Instantly share code, notes, and snippets.

@joshilewis
Created February 5, 2012 14:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joshilewis/1745709 to your computer and use it in GitHub Desktop.
Save joshilewis/1745709 to your computer and use it in GitHub Desktop.
Simple Unit of Work implementation
using System;
namespace ClassLibrary
{
public interface IDependency
{
void SomeMethod(string s);
}
public class MyClass
{
private readonly IDependency dependency;
private readonly Func<IUnitOfWork> startNewUnitOfWork;
public MyClass(IDependency dependency,
Func<IUnitOfWork> startNewUnitOfWork)
{
this.dependency = dependency;
this.startNewUnitOfWork = startNewUnitOfWork;
}
public void DoWork()
{
using (var uow = startNewUnitOfWork())
{
uow.Begin(() => dependency.SomeMethod("hi"));
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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()
{
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();
}
public void Begin(Action action)
{
try
{
Begin();
action.Invoke();
Commit();
}
catch (Exception ex)
{
RollBack();
throw ex;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment