So here's my current unitofwork implementation. This one makes use of the somewhat new current_session_context_class feature. I think this was quite simple compared-some of the others you'll find.
Interface iunitofwork:idisposable { iunitofwork Start (); void BeginTransaction (); void CommitTransaction (); void RollbackTransaction (); }
PublicClass Unitofwork:iunitofwork {#region DependenciesPublic isessionfactory sessionfactory {get; Set }#endregion#region Iunitofwork MembersPublicVirtualvoid BeginTransaction () {var session = Sessionfactory.getcurrentsession ();if (!session. Transaction.isactive) {session. BeginTransaction (); } }PublicVirtualvoid CommitTransaction () {var session = Sessionfactory.getcurrentsession ();if (session. transaction.isactive) {session.Transaction.Commit (); } }public void rollbacktransaction () {var session = Sessionfactory.getcurrentsession (); if (session. Transaction.isactive) {session. Transaction.rollback (); }} public iunitofwork Start () {if (! Currentsessioncontext.hasbind (sessionfactory)) {var session = Sessionfactory.opensession (); session. Flushmode = Flushmode.commit; Currentsessioncontext.bind (session); } return this;} #endregion #region IDisposable members public void Dispose () {var session = Currentsessioncontext.unbind (sessionfactory); var transaction = session. Transaction; if (transaction. IsActive) {transaction. Dispose (); } session. Dispose (); } #endregion}
All of that ' s required are this in the Hibernate config section:
(for Web Apps):
<name= "Current_session_context_class">web</Property>
(For pretty much anything else):
<name= "Current_session_context_class">thread_static</Property>
And just the barebones bootstrapping:
New Configuration (). Configure (). Buildsessionfactory ();
Of course, to-get this-to-work-need to register that sessionfactory instance into your IoC container, and register the Unitofwork type with the container with a transient lifecycle.
From there you can either explicitly create and Dispose iunitofwork instances for each operation, or set up a HttpModule t o Create one at the start of each request and dispose of it in the End_request event.
Yet another to manage your NHibernate isessionfactory