IIS 应用程序池回收后有时会出现错误 "A storage mechanism has already been configured" (NHibernate)

After IIS application pool recycling sometimes an error occurs "A storage mechanism has already been configured" (NHibernate)

我找到了类似的问题"A storage mechanism has already been configured for this application",但没有找到明确的答案。

IIS 应用程序池回收后有时会发生错误"A storage mechanism has already been configured" (NHibernate)。如果出现错误,应用程序将停止工作并因每个请求的错误而崩溃。只有反复回收或iisreset才有帮助。

同样奇怪的是我们在 Application_BeginRequest 方法中初始化 NHibernate(在每个请求上),但无论我在哪里看都是这样做,即使在 Sharp-Architecture examples.

我在 Global.asax 文件中有以下代码:

using System;
using System.Web;
using SharpArch.NHibernate;
using SharpArch.NHibernate.Wcf;

public class GlobalAsax : HttpApplication
{
    private WcfSessionStorage _webSessionStorage;

    public override void Init()
    {
        base.Init();
        _webSessionStorage = new WcfSessionStorage();
    }

    public void Application_Start(object sender, EventArgs e) { }

    public void Application_BeginRequest(object sender, EventArgs e)
    {
        NHibernateInitializer.Instance().InitializeNHibernateOnce(Initialize);
    }

    private void Initialize()
    {
        NHibernateSession.InitStorage(_webSessionStorage); // <- An error occurs here.

        // var configFolder = Server.MapPath(...);
        // NHibernateSession.AddConfiguration(...);
    }
}

NHibernateInitializer class 是单例的,看起来线程安全。方法Initialize必须只执行一次,但事实并非如此。

为什么IIS应用程序池回收后会出现这样的错误?尝试解决此问题的更好方法是什么?

我想我明白了:执行InitStorage后似乎出现了异常。存储已初始化,但标志未就位,我们尝试再次执行此方法。