2011-05-06 12 views
6

Recientemente he pasado de utilizar una ISession directamente a un patrón de tipo de unidad de trabajo de ISession envuelto.Contexto actual de sesión de NHibernate Problema

Solía ​​probar esto usando SQL Lite (en memoria). Tengo una clase auxiliar simple que configura mi SessionFactory, crea una ISession y luego crea el esquema usando SchemaExport y luego devuelve mi ISession y el esquema vivido hasta que cerré la sesión. Cambié esto ligeramente para que ahora configure una SessionFactory, cree una ISession, construya el esquema y pase la fábrica a mi NHibernateUnitOfWork y lo devuelva a mi prueba.

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; 

Internamente, NHibernateUnitOfWork necesita para obtener el ISession que se utilizó para crear el esquema o la base de datos en memoria será en realidad no tienen un esquema, por lo que este es el método que llama para obtener el 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; 
       } 
      } 

El problema es que this.sessionFactory.GetCurrentSession siempre se produce una excepción diciendo que el ICurrentSessionContext no está registrado.

He intentado muchas formas diferentes de establecer la propiedad y diferentes valores (como se puede ver arriba, "thread_static" y mi propio ICurrentSessionContext) pero ninguno parece funcionar.

Alguien tiene algún consejo

Respuesta

14

Prueba esto:

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; 
} 
+0

Este parece haber funcionado, voy a confirmar correctamente el día de hoy y acepto. Gracias – BenCr

+1

Falta un paréntesis al final de la declaración 'if'. – CyberMonk

Cuestiones relacionadas