4

I am trying to get Windsor to give me an instance ISession for each request, which should be injected into all the repositories

Here is my container setup

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<>))
    );

Its based upon a StructureMap post here http://www.kevinwilliampang.com/2010/04/06/setting-up-asp-net-mvc-with-fluent-nhibernate-and-structuremap/

however, when this is run, a new Session is created for every object it is injected too. what am I missing?

(FYI the NHibernateHelper, sets up the config for Nhib)

BenMorel
  • 34,448
  • 50
  • 182
  • 322
dbones
  • 4,415
  • 3
  • 36
  • 52

2 Answers2

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()));
Sly
  • 15,046
  • 12
  • 60
  • 89
2

The ISession should have LifeStyle.PerWebRequest. But you can just use the NHibernate facility instead of manually handling these things.

Andrew Shepherd
  • 44,254
  • 30
  • 139
  • 205
Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275
  • Thanks, I will look into the PerWebRequest. Im not too interested in Facility, as I do not want the dependancy of the SessionManager. – dbones Apr 20 '10 at 09:13
  • You can just ignore ISessionManager and inject ISessionFactory. Or even create an additional factory registration and inject ISession. – Mauricio Scheffer Apr 20 '10 at 11:36