What should be the lifetime of an NHibernate session?

后端 未结 5 802
名媛妹妹
名媛妹妹 2020-12-01 05:00

I\'m new to NHibernate, and have seen some issues when closing sessions prematurely. I\'ve solved this temporarily by reusing sessions instead of opening a session per trans

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-01 05:55

    In a web app, you should have one session per request. This gives you full control over the session lifetime and simplifies error handling.

    In a desktop app, I recommend using a session per presenter (or form if you prefer). To quote Ayende in his MSDN Magazine article:

    The recommended practice for desktop applications is to use a session per form, so that each form in the application has its own session. Each form usually represents a distinct piece of work that the user would like to perform, so matching session lifetime to the form lifetime works quite well in practice. The added benefit is that you no longer have a problem with memory leaks, because when you close a form in the application, you also dispose of the session. This would make all the entities that were loaded by the session eligible for reclamation by the garbage collector (GC).

    There are additional reasons for preferring a single session per form. You can take advantage of NHibernate’s change tracking, so it will flush all changes to the database when you commit the transaction. It also creates an isolation barrier between the different forms, so you can commit changes to a single entity without worrying about changes to other entities that are shown on other forms.

提交回复
热议问题