views:

340

answers:

3

How should I have the NHibernate Session Factory and the sessions for a WinForms application?

Should the SessionFactory be a singleton? Or can I create it every time? What about sessions and transactions?

Any help would be appreciated. Thanks

A: 

Here is an msdn article showing sample application built by Oren Eini (Ayende Rahien): Building a Desktop To-Do Application with NHibernate

Giorgi
+3  A: 

The session factory should be a singleton since it is expensive to create. It is thread safe so there is no threading issue with using it.

I have used the session-per-conversation pattern in winforms applications, and have found it to work well. With this pattern you use the same session for a series of operations that belong together. As I see it, a conversation in a winforms app could, roughly, be mapped to a GUI operation in your application.

Using a new session for every GUI operation helps keep the session small enough to to avoid performance problems with to many entities in the first level cache, while at the same time avoiding using a separate session for every operation, which also can cause performance problems.

To implement this you then create a new session before handling the GUI command, and when the command has been handled you dispose the session. Below is an example of this, which uses a class (PersistenceContext) that creates a session when it is instantiated and disposes the session when it is disposed. This class can then create repositories that use the current session.

public void SomeGuiEvent(...)
{
    using (var context = new PersistenceContext())
    {
        ProcessStuff(context);
    }
}

There are ofcourse many other options of how to implement this, but however you choose to implement it, I can recommend the Session-per-conversation pattern when using NHibernate in a Winforms app.

Erik Öjebo
+2  A: 

This has been asked a few times on Stack Overflow.

The Session Factory should be a singleton, because they are expensive to create.

For Sessions, there seems to be a rough consensus on a "one session per form" approach for NHibernate and WinForms. This means you should open a session when you open a form that accesses your database, and close the session when you close the form.

Look at the answers to this question - http://stackoverflow.com/questions/2013467/what-should-be-the-lifetime-of-an-nhibernate-session - for some more detailed descriptions, and some good links for further reading.

Tom Bushell