NHibernate SessionFactory Thread safe Issue

早过忘川 提交于 2019-12-05 12:33:39

The session factory is threadsafe, the session is not. Building the session factory needs to be protected:

    private static object lockObject = new object();

    private static ISessionFactory SessionFactory
    {
        get
        {
            lock (lockObject)
            {
                if (sessionFactory == null)
                {
                    sessionFactory = Configuration().BuildSessionFactory();
                }
                return sessionFactory;
            }
        }
    }

The session factory is created the first time a thread is requesting a session. This needs to be thread safe to avoid creating the session factory multiple times.

Creating the session by the session factory is thread safe, so you don't need to worry about that.

Sessions are not thread safe in NHibernate by design. So it should be ok as long as you have a session used by only one thread. You can have one NHibernate SessionFactory for multiple threads as long as you have a separate NHibernate session for each thread

for more info have a look at the below link:

https://forum.hibernate.org/viewtopic.php?p=2373236&sid=db537baa5a57e3968abdda5cceec2a24

I suggest use one session for each Request like this:

public ISession GetCurrentSession()
{
        HttpContext context = HttpContext.Current;

        var currentSession = context.Items["session"] as ISession;

        if( currentSession is null )
        {
             currentSession = SessionFactory.GetCurrentSession()
             context.Items["session"] = currentSession;
        }

        return currentSession;
}

Following on from the comment by Stefan Steinegger, I think it would be more efficient to add a null check immediately before the lock, that way you don't need to lock every time if the sessionFactory has already been initialized.

private static object lockObject = new object();

private static ISessionFactory SessionFactory
{
    get
    {
        if (sessionFactory != null)
        {
            return sessionFactory;
        }

        lock (lockObject)
        {
            if (sessionFactory == null)
            {
                sessionFactory = Configuration().BuildSessionFactory();
            }
            return sessionFactory;
        }
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!