class NUnitOfWork : INUnitofWork
{
private NHibernate.ISessionFactory sessionFactory;
private NHibernate.ISession session;
public NHibernate.ISession Session { get { return this.session; } }
private NHibernate.ITransaction transaction;
private static IInternalLogger logger;
private ILogProvider logProvider;
public NUnitOfWork(NHibernate.ISessionFactory sessionFactory, ILogProvider logProvider)
{
this.sessionFactory = sessionFactory;
this.logProvider = logProvider;
logger = logProvider.LoggerFor(typeof(NUnitOfWork));
logger.Debug("Logger acquired successfully.");
}
public void Open()
{
logger.Debug("Open() invoked.");
if (null == this.sessionFactory)
throw new ArgumentNullException("ISessionFactory instance must be available.");
logger.Debug("Trying to acquire ISession instance from ISessionFactory instance.");
this.session = this.sessionFactory.OpenSession();
logger.Info("Acquired ISession instance.");
if (null == this.transaction)
{
logger.Debug("Trying to begin the transaction.");
this.transaction = session.BeginTransaction();
logger.Info("Transaction begun successfully.");
}
else if (null != this.transaction)
{
if (!this.transaction.IsActive)
{
logger.Debug("The current transaction isn't active.");
this.transaction.Begin();
logger.Info("The current transaction is set to active mode now.");
}
}
else
throw new ApplicationException("The current transaction is active.");
}
public void Commit()
{
logger.Debug("Commit() invoked.");
if (null == this.transaction)
throw new ApplicationException("Transaction needs to be open before a calling the commit method.");
this.transaction.Commit();
this.transaction.Dispose();
this.transaction = null;
}
public void Rollback()
{
logger.Debug("Rollback invoked.");
if (null == this.transaction)
throw new ApplicationException("Transaction needs to be open before a calling the Rollback method.");
this.transaction.Rollback();
}
public void Close()
{
logger.Debug("Close() invoked.");
if (null != this.transaction)
{
logger.Debug("Trying to terminate transaction.");
this.transaction.Dispose();
logger.Debug("Transaction disposed successfully.");
}
this.transaction = null;
if (null != this.sessionFactory)
{
if (!this.sessionFactory.IsClosed)
{
if (null != this.Session)
{
if (this.Session.IsOpen)
{
try
{
logger.Debug("Trying to close the session.");
this.Session.Close();
logger.Info("Session closed successfully.");
}
catch (Exception ex)
{
logger.Warn("Unable to close the session.", ex);
}
}
}
logger.Debug("Trying to close ISessionFactory instance.");
this.sessionFactory.Close();
logger.Info("ISessionFactory closed successfully.");
}
else
logger.Debug("ISessionFactory instance is already in a closed state.");
}
}
public void Dispose()
{
logger.Debug("Dispose() invoked.");
this.Close();
}
}
using this code getting error like
Session is closed! Object name: ‘ISession’.
ObjectDisposedException
There is already an open DataReader associated with this Command which must be closed first.