NServiceBus中的NHibernate会话管理与Autofac

时间:2010-07-12 17:18:16

标签: nhibernate nservicebus autofac

Andreas Ohlund有一篇很好的文章here,内容是关于如何使用Structuremap连接NHibernate会话,以便它自动登入NSB事务。

有没有人知道是否可以通过Autofac实现相同的目标?

2 个答案:

答案 0 :(得分:1)

我被一位同事给了我一个白痴

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()
    {
    }
}

公共接口ISessionManager     {         ISession Session {get; }         ISession OpenSession();         bool IsSessionOpened {get; }         void CloseSession();     }

公共类NHibernateSessionManager:ISessionManager     {         private ISessionFactory _sessionFactory;         私人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;
    }
}

答案 1 :(得分:0)

你做的与你提到的articke完全相同,但选择一个Autofac生命周期。如果您希望在其中注入会话的消息处理中涉及其他类,则可以像这样使用InstancePerLifetimeScope

public class EndpointConfig : IConfigureThisEndpoint, AsA_Publisher, IWantCustomInitialization
{

    public void Init()
    {
        var builder = new ContainerBuilder();
        builder.Register(s => SessionFactory.CreateSessionFactory()).As<ISessionFactory>().SingleInstance();
        builder.Register(x => x.Resolve<ISessionFactory>().OpenSession()).As<ISession>().InstancePerLifetimeScope();

        var container = builder.Build();
        Configure.With().AutofacBuilder(container);
    }

}

您还可以在NSB上下文中注册所需的任何其他依赖项,并且由于使用了子容器,您将确保它被实例化并正确配置。