Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manage NHibernate sessions in a long lived Windows forms application?

Tags:

nhibernate

We are using NHibernate to manage our persistence in a complex modular windows forms application - but one thought keeps bothering me. We currently open a session on launch and open all objects through that session. I am worried that all loaded objects get loaded into the NHibernate session cache, so that they cant be garbage collected, and ultimately we will end up with the whole database in memory.

This never happens with web applications because web page requests (and even better Ajax requests) represent the perfect short lived transaction so a session can be opened and closed to handle each request.

However if I load an tree of objects in my forms application and put then into a navigation pane on the screen they may stay their for the life of the application - and at any point the user may click on them, resulting in our code needing to navigate the object relationships to other objects (which only works within an NHibernate session).

What do StackOverflow readers do to keep the benefits of NHibernate without the issues I describe?

like image 781
Ewan Makepeace Avatar asked Dec 05 '08 21:12

Ewan Makepeace


1 Answers

Ayende and company usually recommend using a session per "conversation". This usually makes the session lifetime last for very short operations, so it behaves more like a web app.

For your tree case, you can use Bruno's solution #2 just fine. The objects can be lazily mapped. Then, every time you need to access a child collection, you start a conversation and reconnect the parent via ISession.Lock. Then when the databinding is done, close that session. Not too much overhead to maintain, just a few lines of code in any form that needs to carry a conversation; you can extend Form and the controls you're using to do this automatically if you're feeling sassy.

The tricky part, then, is concurrent edits from different sessions. Let's not go there!

like image 82
Dan Fitch Avatar answered Sep 16 '22 12:09

Dan Fitch