Search code examples
c#iisnhibernatesharp-architecture

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


I have found similar question "A storage mechanism has already been configured for this application" but have not found clear answer.

After IIS application pool recycling sometimes an error occurs "A storage mechanism has already been configured" (NHibernate). In case of an error, the application stops working and crashes with this error for each request. Only repeated recycling or iisreset can helps.

Also is weird that we are initializing NHibernate in Application_BeginRequest method (on each request), but wherever I look everywhere do so, even in Sharp-Architecture examples.

I have the following code in Global.asax file:

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

The NHibernateInitializer class is singleton and looks like thread safe. Method Initialize must be executed only once, but it turns out that this is not so.

Why can such an error occur after IIS application pool recycling? What is the better way try to fix this?


Solution

  • I think I get it: seems like an exception occurs after execution InitStorage. Storage already initialized, but flag is not seated and we try to execute this method again.