TAGS :Viewed: 14 - Published at: a few seconds ago

[ Is there a way to access the current Nhibernate session from anywhere? ]

I have some legacy code that used to open its own Sqlconnection. And I would now like to use the SqlConnection Nhibernate creates.

But I'd rather avoid to change the code a lot (DI, adding loads of settings, ...), so, Is there a simple (convienent) way to get the current Nhibernate session?

Answer 1

No. What is current NHibernate session anyway?

In a web application, each http request must work with its specific NHibernate session(s).

In a desktop application, each screen will probably use one session for each of their actions.

The NHibernate session is not supposed to be used as a singleton.

You should probably use your session factory to open a new NHibernate session in your legacy code then use its CreateSQLQuery method. Your session factory should usually have a singleton lifetime.

If you bound your NHibernate sessions to some context meaningful for your application (such as the HttpContext, CallContext), you may instead get it from there. Beware of cases which may cause contexts losses (async/await configured for not restoring context, asp.net thread agility (do not cause HttpContext losses but CallContext losses), ...).