NullReferenceException when initializing NServiceBus within web application Application_Start method

Posted by SteveBering on Stack Overflow See other posts from Stack Overflow or by SteveBering
Published on 2010-04-28T16:47:24Z Indexed on 2010/04/28 16:53 UTC
Read the original article Hit count: 404

I am running the 2.0 RTM of NServiceBus and am getting a NullReferenceException when my MessageModule binds the CurrentSessionContext to my NHibernate sessionfactory.

From within my Application_Start, I call the following method:

public static void WithWeb(IUnityContainer container)
{
    log4net.Config.XmlConfigurator.Configure();

    var childContainer = container.CreateChildContainer();

    childContainer.RegisterInstance<ISessionFactory>(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);
}

When the bus is started, my message module starts with the following:

public void HandleBeginMessage()
{
    try
    {
        CurrentSessionContext.Bind(_sessionFactory.OpenSession());
    }
    catch (Exception e)
    {
        _log.Error("Error occurred in HandleBeginMessage of NHibernateMessageModule", e);
        throw;
    }
}

In looking at my log, we are logging the following error when the bind method is called:

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)

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?

Thanks, Steve

© Stack Overflow or respective owner

Related posts about nservicebus

Related posts about nhibernate