简体   繁体   中英

NHibernate Session Management Advice

I need some advice on NHibernate Session Management for a C# WinForms application.

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

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

My question relates to Sessions.

  1. Can you only have one session running per thread at all times?

  2. I have a scenario in which a Session (UnitOfWork) may be open for a form shown by the application but the user opens another form (ie Tools - Options) which I would like to have its own UnitOfWork. Clearly in this instance it would make more sense to open another Session for the "Tools - Options" form and not use the currently open session for the underlying form.

  3. Can we have a Dictionary of Sessions on the one thread?

Any advice on session management is appreciated.

+1 on what Jay said. I would also recommend reading Oren Eini's article on Building a Desktop To-Do Application with NHibernate :

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

It uses WPF as the UI technology, but everything he says (wrt NHibernate in desktop apps) is equally relevant for WinForms.

1 - You can have as many sessions as your use case requires.

2 - That's fine, based on 1.

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

What you shouldn't do unless you really know what you're doing and why is:

  • use the same session in more than one thread
  • pass entities from one session/UoW to another
  • attempt to reuse a session that has thrown an exception (don't do this even if you think you know what you are doing)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM