Andreas Ohlund關於如何使用Structuremap來連接NHibernate會話以使其自動登記NSB事務,有一篇出色的文章here。使用Autofac在NServiceBus中進行NHibernate會話管理
有沒有人知道是否有可能實現與Autofac相同?
Andreas Ohlund關於如何使用Structuremap來連接NHibernate會話以使其自動登記NSB事務,有一篇出色的文章here。使用Autofac在NServiceBus中進行NHibernate會話管理
有沒有人知道是否有可能實現與Autofac相同?
我被一個同事給出的awnser
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(); bool IsSessionOpened {get; } void CloseSession(); }
public class NHessionSessionManager: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;
}
}
您的操作與您在提及的說明中完全相同,但選擇了其中一種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範圍內的任何其他的依賴,你一定會很由於使用了子容器而被實例化和正確設置。
會不會在你的系統中引入奇怪的有點鎖? – Baz1nga 2011-03-06 18:04:21