views:

218

answers:

1

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

+1  A: 

I wouldn't use WebSessionContext in this case, precisely because NServiceBus can operate independently of HttpContexts. If you want to use a single session context implementation for both web and NServiceBus message handling, I'd implement NHibernate.Context.ICurrentSessionContext with an hybrid storage, i.e. if HttpContext.Current != null, use the HttpContext as session storage. Otherwise use a thread local storage. This is similar to what Castle ActiveRecord does with its HybridWebThreadScopeInfo.

Mauricio Scheffer
Thanks Mauricio, I will give it a shot.
SteveBering
@SteveBering: I bet someone has already implemented what I describe
Mauricio Scheffer