I have the following code in accessing a database via nhibernate:
ISessionFactory factory = new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory(); using (ISession session = factory.OpenSession()) { ICriteria sc = session.CreateCriteria(typeof(Site)); siteList = sc.List(); session.Close(); } factory.Close();
I wonder whether it is possible to wrap it in this way:
using (var factory= new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory()) { var session = factory.OpenSession(); ICriteria sc = session.CreateCriteria(typeof(Site)); siteList = sc.List(); }
As far as I understand, all the connection inside the using() block will be automatically closed. So I guess that the second statement is fully equivalent to the first.
Am I right?
This is what you usually do:
However you open build your factory just once – at the start of application. You should not really bother by closing it (unless some specific cases) since it’s the application end that cleans it up.
Your factory usually resides in one well defined place – as a singleton.
And to help you understand – using is just c# construct which equals to following: