我觉得我误解了一些东西。请查看以下代码。我设置了DefaultSessionLifeStyleOption.SessionPerTransaction
,但我的会话有不同的会话ID,即使它们在同一个交易中。我期待一个会议,但有两个会议。
我做错了什么,我该怎么做才能做到我想要的?我是否应该将ISession
注入Program
并让我的方法使用该会话?但后来我没有失去SessionManager
与AutoTxFacility
的好处?
using Castle.Facilities.AutoTx;
using Castle.Facilities.FactorySupport;
using Castle.Facilities.NHibernate;
using Castle.Facilities.TypedFactory;
using Castle.MicroKernel.Registration;
using Castle.Transactions;
using Castle.Windsor;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using System;
using System.Transactions;
namespace Sandbox
{
public class DBInstaller : INHibernateInstaller
{
public FluentConfiguration BuildFluent()
{
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008.ConnectionString("Server=localhost;Integrated security=true;"));
}
public Maybe<IInterceptor> Interceptor { get { return Maybe.None<IInterceptor>(); } }
public bool IsDefault { get { return true; } }
public void Registered(ISessionFactory factory) { }
public string SessionFactoryKey { get { return "foo"; } }
}
public class Program
{
public ISessionManager SessionMan { get; set; }
static void Main(string[] args)
{
IWindsorContainer container = new WindsorContainer();
container
.Register(Component.For<INHibernateInstaller>().ImplementedBy<DBInstaller>())
.AddFacility<FactorySupportFacility>() // used by AutoTxFacility, we dont use it directly at this time
.AddFacility<TypedFactoryFacility>() // used by AutoTxFacility, we're probably using it somewhere
.AddFacility<AutoTxFacility>() // automatically manages DB transactions for us, if we want.
.AddFacility<NHibernateFacility>(x => x.DefaultLifeStyle = DefaultSessionLifeStyleOption.SessionPerTransaction)
.Register(
Component.For<Program>().ImplementedBy<Program>().LifestyleTransient());
var p = container.Resolve<Program>();
p.Foo();
}
[Transaction(TransactionScopeOption.Required)]
public virtual void Foo()
{
using (var session = SessionMan.OpenSession())
{
Console.WriteLine("Foo: {0}", ((NHibernate.Impl.SessionImpl)session).SessionId);
Bar();
}
}
public virtual void Bar()
{
using (var session = SessionMan.OpenSession())
{
Console.WriteLine("Bar: {0}", ((NHibernate.Impl.SessionImpl)session).SessionId);
}
}
}
}