I would get the problem is lazy loading with a disposed session. you
dispose the session right after you return the value, if you access
any referenced entities lazy loading would fail because the session is
closed. typically using the session like this is a bad practice. you
cannot take advantage of the NH features because the scope of the
session is so narrow.
var(session = factory.OpenSession())
{
return session.Get<Entity>(id);
}
in terms of a service bus (NServiceBus, Rhino, Mass Transit) the
tyipcal usage would look like this:
message arrives > open session, begin transaction
process message > within handler/consumer & various components inject
the current session (created when the message arrived)
message completes > commit (rollback on error) dispose of transaction
and session.
this means the handlers and services are transient, not singletons. I
use the CurrentSessionContext feature built into NH to manage this for
me. No need for Castle.NhibernateFacility at all.
Rhino service bus has interface IMessageModule. NSB and MT have the
same component, with a different name. it would look like this
class Uow : IMessageModule
{
public class Uow(ISessionFactory factory)
{
this.factory = factory
}
public void Init(ITransport transport)
{
transport.MesasgeArrived += OpenSession;
transport.MesasgeCompleted += CompleteSession;
}
public void Stop(ITransport transport)
{
transport.MesasgeArrived -= OpenSession;
transport.MesasgeCompleted -= CompleteSession;
}
private bool OpenSession(MessageInformation info)
{
if(CurrentSessionContext.HasBind(factory)) return false;
var session = factory.OpenSession();
session.BeginTransaction();
CurrentSessionContext.Bind(session)
return false;
}
private void CompleteSession(MessageInformation info, Exception e)
{
if(CurrentSessionContext.HasBind(factory) == false) return;
using(var session = CurrentSessionContext.Unbind(factory))
using(var tx = session.Transaction)
{
if(e == null)
tx.Commit();
else
tx.Rollback();
}
}
}
you can then reference the current session using
factory.GetCurrentSession();
in the config file add
<property name="current_session_context">thread</property>