0

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?

4

2 回答 2

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 会话 { 获取;} ISession OpenSession(); 布尔 IsSessionOpened { 获取;} 无效关闭会话();}

公共类 NHibernateSessionManager : ISessionManager { 私有 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;
    }
}
于 2010-07-13T16:16:14.900 回答
1

您所做的与您提到的文章中的完全相同,但选择了 Autofac lifescopes 之一。如果您希望在其中注入会话的消息处理中涉及其他类,则可以像这样使用 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 上下文中注册您需要的任何其他依赖项,并且由于使用子容器,您将确保它被正确实例化和处理。

于 2012-12-11T16:00:21.223 回答