Skip to content

Instantly share code, notes, and snippets.

@fabiomaulo
Created June 19, 2010 18:39
Show Gist options
  • Save fabiomaulo/445142 to your computer and use it in GitHub Desktop.
Save fabiomaulo/445142 to your computer and use it in GitHub Desktop.
// config
<property name="current_session_context_class">
uNhAddIns.SessionEasier.Contexts.ThreadLocalSessionContext, uNhAddIns
</property>
// class impl
public class PersistenceRequest: IDisposable
{
private bool disposed;
private readonly ISessionFactory factory;
public PersistenceRequest()
{
factory = ServiceLocator.Current.GetInstance<ISessionFactory>();
BeginRequest();
}
~PersistenceRequest()
{
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
EndRequest();
}
disposed = true;
}
}
private void BeginRequest()
{
factory.GetCurrentSession().BeginTransaction();
}
private void EndRequest()
{
ISession session = factory.GetCurrentSession();
try
{
if (session.Transaction.IsActive)
{
session.Transaction.Commit();
}
}
catch (Exception)
{
if (session.Transaction.IsActive)
{
session.Transaction.Rollback();
}
throw;
}
finally
{
session.Dispose();
}
}
}
// example of usage
var m = new Magazine(Countries.Mexico, 1) { Title = "some title", NickName = "salondemilan" };
var dao = new EntityDao<Magazine>(ServiceLocator.Current.GetInstance<ISessionFactory>());
using (new PersistenceRequest())
{
dao.Executing(d=> d.MakePersistent(m)).NotThrows();
}
var poid = m.Id;
using (new PersistenceRequest())
{
var e = dao.Get(poid);
e.Should().Not.Be.Null();
e.Title.Should().Be.EqualTo("some title");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment