tags:

views:

137

answers:

4

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?

+1  A: 

Your 2nd code example has at least one bad practice: you're building your SessionFactory, and afterwards you destroy it. So, I assume that you build your SessionFactory each time you need to have a session ?

Building the factory is quite expensive.

Frederik Gheysels
In most real world cases this piece will be in a Singleton and the ISession reused,closed on Session end. I see your point though.
Cherian
+1  A: 

Yes. If the Session object implements IDisposable, that should be its semantics. If it isn't, NHibernate is broken by design.

Pontus Gagge
A: 
var factory= new NHibernate.Cfg.Configuration().Configure().BuildSessionFactory())

Take a look at http://en.wikipedia.org/wiki/Principle_of_least_knowledge and why this code snippet is code smell. Try to wrap/encapsulate such construction code away from your client code. Perhaps by providing ISessionFactory as a parameter to the constructor of your class.

Igor Brejc
+2  A: 

This is what you usually do:

        using (ISession session = factory.OpenSession()) {

            ICriteria sc = session.CreateCriteria(typeof(Site));
            siteList = sc.List();
        }

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:

try {
   ISession session = sf.OpenSession();
   .....
} finally {
   session.Dispose();
}
Rashack
Minor point, but for completeness, I believe there is a null check before session.Dispose is invoked, in case session doesn't implement IDisposable.
Si
If the class in question does not implement IDisposable it won't compile. But yes - it makes sense that there is nullability check.
Rashack