Windsor + NHibernate + ISession + MVC

时间:2010-04-19 23:39:39

标签: asp.net-mvc nhibernate castle-windsor

我想让Windsor为每个请求提供一个实例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。我错过了什么?

(仅供参考NHibernateHelper,为Nhib设置配置)

2 个答案:

答案 0 :(得分: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()));

答案 1 :(得分:2)

ISession应该有LifeStyle.PerWebRequest。但您可以使用NHibernate facility而不是手动处理这些内容。