views:

84

answers:

1

Andreas Ohlund has an excellent article here on how to use Structuremap to wire the NHibernate session so that it enlists in the NSB transaction automatically.

Does anyone know if it is possible to achieve the same with Autofac?

A: 

I have been given the awnser by a colleague

public class NHibernateMessageModule : IMessageModule
{
    /// <summary>
    /// Injected SessionManager.
    /// </summary>
    public ISessionManager SessionManager { get; set; }

    public void HandleBeginMessage()
    {
        //this session need for NServiceBus and for us
        ThreadStaticSessionContext.Bind(SessionManager.OpenSession()); //CurrentSessionContext or  ThreadStaticSessionContext
    }

    public void HandleEndMessage()
    {
        SessionManager.Session.Flush();
    }

    public void HandleError()
    {
    }
}

public interface ISessionManager { ISession Session { get; } ISession OpenSession(); bool IsSessionOpened { get; } void CloseSession(); }

public class NHibernateSessionManager : ISessionManager { private ISessionFactory _sessionFactory; private ISession _session;

    public ISession Session
    {
        get { return _session; } 
        private set { _session = value; }
    }

    public SchemaExport SchemaExport { get; set; }


    public NHibernateSessionManager(ISessionFactory sessionFactory)
    {
        _sessionFactory = sessionFactory;
    }

    public bool IsSessionOpened
    {
        get { return Session != null && Session.IsOpen; } 
    }

    public ISession OpenSession()
    {
        if(Session == null)
        {
            Session = _sessionFactory.OpenSession();
            if (SchemaExport != null)
                SchemaExport.Execute(true, true, false, Session.Connection, null);
        }
        return Session;
    }

    public void CloseSession()
    {
        if (Session != null && Session.IsOpen)
        {
            Session.Flush();
            Session.Close();
        }
        Session = null;
    }
}
Charlie Barker