NHibernate Session Management Best Practices

I need some tips on NHibernate session management for a C # WinForms application.

I am currently porting the application to use NHibernate. I also use the UnitOfWork pattern as described in the link below;

http://nhforge.org/wikis/patternsandpractices/nhibernate-and-the-unit-of-work-pattern.aspx

My question is about sessions.

  • Can you have only one session running in a thread?

  • I have a scenario in which a session (UnitOfWork) can be opened for the form shown by the application, but the user opens another form (e.g. Tools - Options) that I would like to have my own UnitOfWork. Obviously, in this case it would be more reasonable to open another session for the "Tools - Options" form, and not use the current open session for the base form.

  • Can we have a dictionary of sessions in one thread?

Any recommendations for managing sessions are welcome.

+6
c # session winforms nhibernate
source share
2 answers

+1 about what Jay said. I would also recommend reading Oren Eini's article on creating a desktop application with NHibernate:

http://msdn.microsoft.com/en-us/magazine/ee819139.aspx

It uses WPF as its user interface technology, but everything it says (at the NHibernate address in desktop applications) applies equally to WinForms.

+4
source share

1 - You can have as many sessions as you need to use.

2 - This is a penalty based on 1.

3 - You can put session variables in a dictionary or any other collection.

What you should not do if you do not know what you are doing, and why:

  • use the same session in more than one thread
  • transfer objects from one session / UoW to another
  • try reusing the session that threw the exception (do not do this even if you think you know what you are doing)
+3
source share

All Articles