Olegs Jasjko
Olegs Jasjko

Reputation: 2088

How to enable multi-threading in NHibernate session?

I am calling procedure with param this way (by using NHibernate session):

var session = (NHibernate.ISession)GetConnection("BookDataBase");//NHibernate.ISession
var query = session.CreateSQLQuery("exec UpdateBook @BookId=:bookid");
query.SetInt32("bookid", bookId);
query.ExecuteUpdate();

After several investigation after this question, as I understand, NHibernate.ISession is mentioned to be session-per-request. So, because sometimes I am trying to run 2 procedures simultaneously, first works normally, but second one fails with

Transaction not connected, or was disconnected

So I need to somehow enable multitasking for ISession, or at least make it possible to do run procedures simultaneously.

How can I accomplish this? (Most of links that I found are explaining that this situation are happening, but it didn't help to fix it).

Upvotes: 1

Views: 1577

Answers (2)

Low Flying Pelican
Low Flying Pelican

Reputation: 6054

In this instance you should use sessionFactory, like

ISessionFactory sessionFactory = //get the factory
using (session = sessionFactory.OpenSession())
using (tx = session.BeginTransaction())
{
  var query = session.CreateSQLQuery("exec UpdateBook @BookId=:bookid");
  query.SetInt32("bookid", bookId);
  query.ExecuteUpdate();
  tx.Commit();
}

There are many ways to achieve this, depending on your application. For example you can create sessions per request if it's a web application.

Upvotes: 0

sm_
sm_

Reputation: 2602

The session context is determined as per your configuration, probably in your DI container (if you're using any), or in your own wrapper class; so if it is not in your DI contatiner, then you probably should follow the code of the function you mentioned in your question GetConnection(String databaseName) you should be able to figure out, what is the session context.

The session context could be 'Per-request', 'Per-thread' or even a singleton over the application scope (not recommended of course).

Now to answer your question, i can't determine, with information you provided only, if you should proceed to use the same session object over multiple threads (if that is the case for you now), however i advise you to use a session-per-thread context over threads only, and use session-per-request context serving requests coming through the UI or API that don't require long processing times, this way you would make the most of use from the session level cache in both cases.

Upvotes: 2

Related Questions