global.asax Application_BeginRequest中的NHibernate会话

时间:2015-10-12 22:06:57

标签: c# wcf nhibernate

我正在尝试在Global.asax和Application_BeginRequest中启动一个hibernate会话,然后访问Global.asax上的静态SessionFactory以获取WCF服务中的当前会话。

然而,我得到"对象引用未设置为对象的实例"当我尝试在服务中获取当前会话时。我正在使用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 个答案:

答案 0 :(得分:0)

我看到后发现<property name="current_session_context_class">web</property>改为<property name="current_session_context_class">call</property>https://groups.google.com/forum/#!topic/nhusers/jo9TJOKXWlI 它正在运作