Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>This issue was why I created a simple UnitOfWork that combines ISession and ITransaction.</p> <p>In tests, I would write the following code:</p> <pre><code>var product = new Product {Name = "Apple", Category = "Fruits"}; using (var session = _sessionFactory.OpenSession()) using (var transaction = _session.BeginTransaction()) { session.Save(product); transaction.Commit(); } </code></pre> <p>when I really wanted:</p> <pre><code>var product = new Product {Name = "Apple", Category = "Fruits"}; using (var unitOfWork = new UnitOfWork(_sessionFactory)) { unitOfWork.CurrentSession.Save(product); unitOfWork.Commit(); } </code></pre> <p>Here is my unit of work implementation,</p> <pre><code>using NHibernate; namespace NHibernateBootstrap.Core.Persistence { 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(); } } } </code></pre> <p>As far as the when to call Commit() (either using ITransaction or UnitOfWork), I believe that it should be done explicitly before the end of your request. If you don't call it, then the UnitOfWork should clean itself up, but not commit. Alternatively, you could use an HttpModule to commit in an EndRequest handler.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload