title: Correct use of the NHibernate Unit Of Work pattern and Ninject
body: <p>I have the following implementation and would like some feedback as to whether it makes correct use of NHibernate for sessions and transactions.</p>
  
  <pre><code>public interface IUnitOfWork : IDisposable
  {
      ISession CurrentSession { get; }
      void Commit();
      void Rollback();
  }
  
  public class UnitOfWork : IUnitOfWork
  {
      private readonly ISessionFactory _sessionFactory;
      private readonly ITransaction _transaction;
  
      public UnitOfWork(ISessionFactory sessionFactory)
      {
          _sessionFactory = sessionFactory;
          CurrentSession = _sessionFactory.OpenSession();
          _transaction = CurrentSession.BeginTransaction();
      }
  
      public ISession CurrentSession { get; private set; }
  
      public void Dispose()
      {
          CurrentSession.Close();
          CurrentSession = null;
      }
  
      public void Commit()
      {
          _transaction.Commit();
      }
  
      public void Rollback()
      {
          if (_transaction.IsActive) _transaction.Rollback();
      }
  }
  </code></pre>
  
  <p>Ninject binding</p>
  
  <pre><code>Bind&lt;IUnitOfWork&gt;().To&lt;UnitOfWork&gt;().InTransientScope();
  Bind&lt;ISessionFactory&gt;().ToProvider&lt;NHibernateSessionFactoryProvider&gt;().InSingletonScope();
  Bind&lt;IRepository&gt;().To&lt;Repository&gt;().InTransientScope();
  </code></pre>
  
  <p>Here is an example of the usage:</p>
  
  <pre><code>public class Repository : IRepository
  {
      private readonly ISessionFactory _sessionFactory;
  
      public Repository(ISessionFactory sessionFactory)
      {
          _sessionFactory = sessionFactory;
      }
  
      public void Add(IObj obj)
      {
          using (var unitOfWork = new UnitOfWork(_sessionFactory))
          {
              unitOfWork.CurrentSession.Save(obj);
              unitOfWork.Commit();
          }         
      }
  }
  </code></pre>
  
  <p>In my previous implementation I would inject IUnitOfWork into my repository constructor like so</p>
  
  <pre><code>public Repository(IUnitOfWork unitOfWork)
      {...
  </code></pre>
  
  <p>But the Dispose() method would not execute causing a subsequent call to throw this exception: "Cannot access a disposed object. Object name: 'AdoTransaction'." </p>