title: NullReferenceException when initializing NServiceBus within web application Application_Start method
body: <p>I am running the 2.0 RTM of NServiceBus and am getting a NullReferenceException when my MessageModule binds the CurrentSessionContext to my NHibernate sessionfactory.</p>
  
  <p>From within my Application_Start, I call the following method:</p>
  
  <pre><code>public static void WithWeb(IUnityContainer container)
  {
      log4net.Config.XmlConfigurator.Configure();
  
      var childContainer = container.CreateChildContainer();
  
      childContainer.RegisterInstance&lt;ISessionFactory&gt;(NHibernateSession.SessionFactory);
  
      var bus = NServiceBus.Configure.WithWeb()
          .UnityBuilder(childContainer)
          .Log4Net()
          .XmlSerializer()
          .MsmqTransport()
          .IsTransactional(true)
          .PurgeOnStartup(false)
          .UnicastBus()
          .ImpersonateSender(false)
          .LoadMessageHandlers()
          .CreateBus();
  
      var activeBus = bus.Start();
  
      container.RegisterInstance(typeof(IBus), activeBus);
  }
  </code></pre>
  
  <p>When the bus is started, my message module starts with the following:</p>
  
  <pre><code>public void HandleBeginMessage()
  {
      try
      {
          CurrentSessionContext.Bind(_sessionFactory.OpenSession());
      }
      catch (Exception e)
      {
          _log.Error("Error occurred in HandleBeginMessage of NHibernateMessageModule", e);
          throw;
      }
  }
  </code></pre>
  
  <p>In looking at my log, we are logging the following error when the bind method is called:</p>
  
  <pre><code>System.NullReferenceException: Object reference not set to an instance of an object.
  at NHibernate.Context.WebSessionContext.GetMap()
  at NHibernate.Context.MapBasedSessionContext.set_Session(ISession value)
  at NHibernate.Context.CurrentSessionContext.Bind(ISession session)
  </code></pre>
  
  <p>Apparently, there is some issue in getting access to the HttpContext. Should this call to configure NServiceBus occur later in the lifecycle than Application_Start? Or is there another workaround that others have used to get handlers working within an Asp.NET Web application?</p>
  
  <p>Thanks,
  Steve</p>