Windsor + NHibernate + ISession + MVC

4
我希望您能为我提供每个请求的ISession实例,该实例应注入到所有存储库中。以下是我的容器设置:
container.AddFacility<FactorySupportFacility>().Register(
    Component.For<ISessionFactory>().Instance(NHibernateHelper.GetSessionFactory()).LifeStyle.Singleton,
    Component.For<ISession>().LifeStyle.Transient
        .UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>().OpenSession())
    );

//add to the container
container.Register(
    Component.For<IActionInvoker>().ImplementedBy<WindsorActionInvoker>(),
    Component.For(typeof(IRepository<>)).ImplementedBy(typeof(NHibernateRepository<>))
    );

基于这篇StructureMap的文章http://www.kevinwilliampang.com/2010/04/06/setting-up-asp-net-mvc-with-fluent-nhibernate-and-structuremap/,然而,当它运行时,每个被注入的对象都会创建一个新的Session。我错过了什么吗?(FYI,NHibernateHelper为Nhib设置了配置)
2个回答

9
container.AddFacility<FactorySupportFacility>();
container.Register(Component.For<ISessionFactory>()
                            .LifeStyle.Singleton
                            .UsingFactoryMethod(() => new NhibernateConfigurator().CreateSessionFactory()));

container.Register(Component.For<ISession>()
                            .LifeStyle.PerWebRequest
                            .UsingFactoryMethod(kernel => kernel.Resolve<ISessionFactory>().OpenSession()));

2
ISession应该采用LifeStyle.PerWebRequest。但你可以使用NHibernate facility来替代手动处理这些事情。请参考NHibernate facility获取更多信息。

谢谢,我会研究PerWebRequest。我对Facility不太感兴趣,因为我不想依赖SessionManager。 - dbones
你可以直接忽略ISessionManager,并注入ISessionFactory。甚至可以创建一个额外的工厂注册并注入ISession。 - Mauricio Scheffer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接