NHibernate SessionFactory Thread safe Issue?

The session factory is threadsafe, the session is not. Building the session factory needs to be protected.

The session factory is threadsafe, the session is not. Building the session factory needs to be protected: private object lockObject = new object(); private static ISessionFactory SessionFactory { get { lock (lockObject) { if (sessionFactory == null) { sessionFactory = Configuration(). BuildSessionFactory(); } return sessionFactory; } } } The session factory is created the first time a thread is requesting a session.

This needs to be thread safe to avoid creating the session factory multiple times. Creating the session by the session factory is thread safe, so you don't need to worry about that.

Thanks for that Stefan. Quick question regarding lock in the above code. The lock ensures that each thread has its own SessionFactory and two or more Session factory are not created on the same thread?

– Bobby Sep 9 at 11:08 No, the lock lets the first thread come in and create the static session factory. The second thread needs to wait until the first is leaving the lock scope. When the second comes in, the session factory had been created and it just takes it.

Without the lock, the session factory is created multiple times in parallel. – Stefan Steinegger Sep 9 at 12:44 That makes sense perfect :o) – Bobby Sep 9 at 12:46.

Sessions are not thread safe in N So it should be ok as long as you have a session used by only one thread. You can have one Nbernate SessionFactory for multiple threads as long as you have a separate Nbernate session for each thread for more info have a look at the below link: https://forum.hibernate. Org/viewtopic.

Php? P=2373236&sid=db537baa5a57e3968abdda5cceec2a24.

I suggest use one session for each Request like this: public ISession GetCurrentSession() { HttpContext context = HttpContext. Current; var currentSession = context. Items"session" as ISession; if( currentSession is null ) { currentSession = SessionFactory.

GetCurrentSession() context. Items"session" = currentSession; } return currentSession; }.

Sessions are not thread safe in NHibernate by design. So it should be ok as long as you have a session used by only one thread. You can have one NHibernate SessionFactory for multiple threads as long as you have a separate NHibernate session for each thread.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions