R – FluentNHibernate and Not Recognizing the Session

nhibernate

For some reason the Nhibernate is chocking out when I try to access the session. It is throwing the following exception:

No CurrentSessionContext configured (set the property current_session_context_class)!

Please note I am not using XML to setup the configuration!

I am opening the session in my test:

 [SetUp]
        public void Initialize()
        {
             _session = GetSessionFactory().OpenSession(); 
            _transaction = _session.BeginTransaction();

            SetupContext(); 
            When(); 
        }

and then I am using Repository to access the current session. The repository is in different dll.

public void Save(Category newCategory)
        {
            var session = SessionFactory.GetSession(); 
            session.SaveOrUpdate(newCategory);
        }





  public static ISession GetSession()
        {
            var session = _sessionFactory.GetCurrentSession(); 

            if (session == null)
                return _sessionFactory.OpenSession();

            return session; 
        }

UPDATE:

In my BaseTest.cs class I also have a teardown:

[TearDown]
public void CleanUp()
{
_session.Dispose();
_transaction.Dispose();
}

During debugging it seems like the CleanUp is being fired and killing the _session object!

Another update: I have added the following code when building the configuration:

public static ISessionFactory CreateSessionFactory()
        {
             _sessionFactory = 
                Fluently.Configure().Database(
                    MsSqlConfiguration.MsSql2000.ConnectionString(
                        c => c.FromConnectionStringWithKey("ConnectionString")))
                        .Mappings(m =>  
      m.FluentMappings.AddFromAssemblyOf<Category>())
      **.ExposeConfiguration(x =>
      {
          x.SetProperty("current_session_context_class",
  "thread_static");
      })**
      .BuildSessionFactory();

            return _sessionFactory; 
        }

Now I get the following error:

No session bound to the current context

Best Answer

You need to bind the session to the current context.

In the setup method:

var session = SessionFactory.OpenSession();
CurrentSessionContext.Bind(session);

And in the teardown method:

var session = CurrentSessionContext.Unbind(SessionFactory);
session.Dispose();
Related Topic