NHibernate Session Context Issue

I recently switched from using ISession directly to a wrapped template like ISession.

I tested this with SQL Lite (in memory). I have a simple helper class that sets up my SessionFactory, created an ISession, and then built a circuit using SchemaExport, and then returned my ISession, and the circuit continued until the session closed. I changed this a bit, so now I am setting up a SessionFactory, creating an ISession, creating a schema and passing the factory to my NHibernateUnitOfWork and returning it to my test.

var databaseConfiguration = SQLiteConfiguration.Standard.InMemory() .Raw("connection.release_mode", "on_close") .Raw("hibernate.generate_statistics", "true"); var config = Fluently.Configure().Database(databaseConfiguration).Mappings( m => { foreach (var assembly in assemblies) { m.FluentMappings.AddFromAssembly(assembly); m.HbmMappings.AddFromAssembly(assembly); } }); Configuration localConfig = null; config.ExposeConfiguration(x => { x.SetProperty("current_session_context_class", "thread_static"); // typeof(UnitTestCurrentSessionContext).FullName); localConfig = x; }); var factory = config.BuildSessionFactory(); ISession session = null; if (openSessionFunction != null) { session = openSessionFunction(factory); } new SchemaExport(localConfig).Execute(false, true, false, session.Connection, null); UnitTestCurrentSessionContext.SetSession(session); var unitOfWork = new NHibernateUnitOfWork(factory, new NHibernateUTCDateTimeInterceptor()); return unitOfWork; 

Inside, NHibernateUnitOfWork must get the ISession that was used to create the schema, or the database in memory does not actually have the schema, so this is the method it calls to get the ISession.

 private ISession GetCurrentOrNewSession() { if (this.currentSession != null) { return this.currentSession; } lock (this) { if (this.currentSession == null) { // get an existing session if there is one, otherwise create one ISession session; try { session = this.sessionFactory.GetCurrentSession(); } catch (Exception ex) { Debug.Write(ex.Message); session = this.sessionFactory.OpenSession(this.dateTimeInterceptor); } this.currentSession = session; this.currentSession.FlushMode = FlushMode.Never; } } 

The problem is that this.sessionFactory.GetCurrentSession always throws an exception saying that ICurrentSessionContext not registered.

I tried many different ways to set the property and different values ​​(as you can see above, "thread_static" and my own ICurrentSessionContext ), but no one works.

Anyone got advice

+7
source share
1 answer

Try the following:

 try { if (NHibernate.Context.CurrentSessionContext.HasBind(sessionFactory)) { session = sessionFactory.GetCurrentSession(); } else { session = sessionFactory.OpenSession(this.dateTimeInterceptor); NHibernate.Context.CurrentSessionContext.Bind(session); } } catch (Exception ex) { Debug.Write(ex.Message); throw; } 
+15
source

All Articles