NHibernate Session in global.asax Application_BeginRequest

会有一股神秘感。 提交于 2019-12-25 03:01:05

问题


I am trying to start a hibernate session in Global.asax and Application_BeginRequest and then access a static SessionFactory on Global.asax to get the current session in a WCF service.

However I get "Object reference not set to an instance of an object" when I try to get the current session inside the service. I am accessing the service using basicHttpBinding.

Global.asax

public class Global : System.Web.HttpApplication
{
        public static ISessionFactory SessionFactory { get; private set; }

        protected void Application_Start(object sender, EventArgs e)
        {
            //Initialize session factory and set up mappings
        }


        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            var session = SessionFactory.OpenSession();
            CurrentSessionContext.Bind(session);
        }

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            var session = CurrentSessionContext.Unbind(SessionFactory);
            if (session != null)
            {
                if (session.Transaction != null &&
                    session.Transaction.IsActive)
                {
                    session.Transaction.Rollback();
                }
                else
                    session.Flush();
                session.Close();
            }
        }

}

MyService.svc

public class MyService : IMyService
{
   public void doStuff()
   {
      //Exception occurs here. Session Factory is not null. But GetCurrentSession() gives exception.
      ISession session = Global.SessionFactory.GetCurrentSession();

   }
} 

Hibernate Config

  <hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
    <session-factory>
      <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
      <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
      <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
      <property name="connection.connection_string">...</property>
      <property name="current_session_context_class">web</property>
    </session-factory>
  </hibernate-configuration>

回答1:


I changed <property name="current_session_context_class">web</property> to <property name="current_session_context_class">call</property> after seeing this: https://groups.google.com/forum/#!topic/nhusers/jo9TJOKXWlI and it is working



来源:https://stackoverflow.com/questions/33090991/nhibernate-session-in-global-asax-application-beginrequest

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!