We do a little different than bigglesby, and I do not say that he is mistaken or that our perfection.
In global.asax, we have when starting the application:
... protected void Application_Start() { ISessionFactory sf = DataRepository .CreateSessionFactory( ConfigurationManager .ConnectionStrings["conn_string"] .ConnectionString );
We have our DataRepository: NOTE: (this is not a repository - my design error: a bad name - it looks more like your NHibernateHelper, I suppose it's more like some kind of NH configuration shell ...)
.... public static ISessionFactory CreateSessionFactory(string connectionString) { if (_sessionFactory == null){ _sessionFactory = Fluently.Configure() .Database(MsSqlConfiguration ... ...
The thing with a factory session is that you do not want to generate / build one for each request. The DataRepository acts like a singleton, ensuring that the factory session is created only once, and this starts when the application starts. In our base controller, we enter either a session or sessionfactory into our controllers (some controllers do not require a database connection, so they get from the base controller without a database) using WindosrCastle. Our WindsorControllerFactory we have:
... //constructor public WindsorControllerFactory(ISessessionFactory) { Initialize(); // Set the session Factory for NHibernate _container.Register( Component.For<ISessionFactory>() .UsingFactoryMethod( () => sessionFactory) .LifeStyle .Transient ); } private void Initialize() { _container = new WindsorContainer( new XmlInterpreter( new ConfigResource("castle") ) ); _container.AddFacility<FactorySupportFacility>(); // Also register all the controller types as transient var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes() where typeof(IController).IsAssignableFrom(t) select t; foreach (var t in controllerTypes) { _container.AddComponentLifeStyle(t.FullName, t, LifestyleType.Transient); } } ....
With this setting, each request generates an NHibernate session, and with our design we can also have controllers that do not generate sessions. And this is currently how it works for us.
May I also say that I found NHProf very useful when trying to configure or debug the problem we had.
Dai bok
source share