No session associated with current context

I followed this guide: http://nhforge.org/blogs/nhibernate/archive/2011/03/03/effective-nhibernate-session-management-for-web-apps.aspx

When I try to load a page (mvc 3), I do not receive a message stating that there is no connection with the current context.

public static ISessionFactory BuildSessionFactory() { return Fluently.Configure() .Database(MsSqlConfiguration.MsSql2008 // .ConnectionString(@"Server=.\SQLExpress;Database=db1;Uid=dev;Pwd=123;") .ShowSql()) //.ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web")) //.CurrentSessionContext<CallSessionContext>() .Mappings(m => m.FluentMappings .AddFromAssemblyOf<User>()) .ExposeConfiguration(cfg => new SchemaExport(cfg) .Create(false, false)) .BuildSessionFactory(); } 

The actual error is in my Repository.cs file:

Line 114: public virtual T Get (int id) Line 115: {Line 116: return _sessionFactory.GetCurrentSession (). Get (id); Line 117:} Line 118:

When I debugged it, _sessionFactory was not null or nothing, it just cannot find the associated session.

I have an httpmodule connected to my web.config and it starts so that there is no problem.

In my nhibernate configuration, I tried both:

 .ExposeConfiguration(c => c.SetProperty("current_session_context_class", "web")) 

and

 .CurrentSessionContext<CallSessionContext>() 

But that did not work.

+6
source share
1 answer

It doesn't seem like you are tying your session to context. Take a look below:

 public class SessionFactory { protected static ISessionFactory sessionFactory; private static ILog log = LogManager.GetLogger(typeof(SessionFactory)); //Several functions omitted for brevity public static ISession GetCurrentSession() { if(!CurrentSessionContext.HasBind(GetSessionFactory())) CurrentSessionContext.Bind(GetSessionFactory().OpenSession()); return GetSessionFactory().GetCurrentSession(); } public static void DisposeCurrentSession() { ISession currentSession = CurrentSessionContext.Unbind(GetSessionFactory()); currentSession.Close(); currentSession.Dispose(); } } 

The key to the above is that whenever you retrieve your first session, you associate it with any context that you use.

+8
source

Source: https://habr.com/ru/post/897522/


All Articles