【问题标题】:NullReferenceException when initializing NServiceBus within web application Application_Start method在 Web 应用程序 Application_Start 方法中初始化 NServiceBus 时出现 NullReferenceException
【发布时间】:2011-02-13 11:01:04
【问题描述】:

我正在运行 NServiceBus 的 2.0 RTM,当我的 MessageModule 将 CurrentSessionContext 绑定到我的 NHibernate sessionfactory 时,我得到了 NullReferenceException。

从我的 Application_Start 中,我调用以下方法:

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);
}

当总线启动时,我的消息模块开始如下:

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

在查看我的日志时,我们在调用绑定方法时记录了以下错误:

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)

显然,访问 HttpContext 存在一些问题。这个配置 NServiceBus 的调用是否应该在生命周期中发生在 Application_Start 之后?或者是否有其他人用来让处理程序在 Asp.NET Web 应用程序中工作的另一种解决方法?

谢谢, 史蒂夫

【问题讨论】:

    标签: asp.net nhibernate nservicebus nullreferenceexception


    【解决方案1】:

    在这种情况下我不会使用 WebSessionContext,正是因为 NServiceBus 可以独立于 HttpContexts 运行。如果您想为 web 和 NServiceBus 消息处理使用单个会话上下文实现,我将使用混合存储实现 NHibernate.Context.ICurrentSessionContext,即如果 HttpContext.Current != null,则使用 HttpContext 作为会话存储。否则使用线程本地存储。这与 Castle ActiveRecord 对其HybridWebThreadScopeInfo 所做的类似。

    【讨论】:

    • 谢谢 Mauricio,我会试一试的。
    • @SteveBering:我敢打赌有人已经实现了我所描述的
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 2017-01-10
    • 1970-01-01
    • 2021-11-05
    • 2020-01-20
    • 1970-01-01
    相关资源
    最近更新 更多