We want to take advantage of nHibernate's "Unit of Work" functionality. To accomplish this in our C# WinForms app, we need to open a session from within the UI layer i.e when a form opens. Perform some work and then close the session when we close the form.
This form based approach seems very logical except for the fact that we now require a reference to nHibernate from our UI layer! Where should we be referencing nHibernate, I would have though开发者_运维问答t we can accomplish thish without having to reference it from within our UI layer?
You need a session manager class, which would be a wrapper for binding the nhibernate session. Something like this:
public class SessionManager : ISessionManager
{
private readonly ISessionFactory _sessionFactory;
SessionManager()
{
_sessionFactory = CreateSessionFactory();
}
public void OpenSession()
{
ISession session = _sessionFactory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session);
}
public void CloseSession()
{
ISession session = CurrentSessionContext.Unbind(_sessionFactory);
if (session == null) return;
try
{
session.Transaction.Commit();
}
catch (Exception)
{
session.Transaction.Rollback();
}
finally
{
session.Close();
session.Dispose();
}
}
}
Just create the CreateSessionFactory method.
精彩评论