【问题标题】:Windsor + NHibernate + ISession + MVC温莎 + NHibernate + ISession + MVC
【发布时间】:2010-04-19 23:39:39
【问题描述】:

我试图让 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 设置配置)

【问题讨论】:

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


    【解决方案1】:
    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 而不是手动处理这些事情。

      【讨论】:

      • 谢谢,我会调查 PerWebRequest。我对 Facility 不太感兴趣,因为我不想依赖 SessionManager。
      • 你可以忽略 ISessionManager 并注入 ISessionFactory。甚至创建一个额外的工厂注册并注入 ISession。
      猜你喜欢
      • 2014-01-15
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多