Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nhibernate session management strategy for web application with background-workers?

For a web application, it seems like a good way to handle the session is to use the setting <property name="current_session_context_class">managed_web</property>, call CurrentSessionContext.Bind/Unbind on Begin/EndRequest. Then I can just use sessionFactory.GetCurrentSession() in the repository class.

This works fine for all page request. But I have background workers doing stuff and using the same repository classes to do stuff. These do not run within a web request, so that session handling won't work.

Any suggestions to how this can be solved?

like image 288
Allrameest Avatar asked May 02 '11 06:05

Allrameest


1 Answers

I solved it by creating my own session context class:

public class HybridWebSessionContext : CurrentSessionContext
{
    private const string _itemsKey = "HybridWebSessionContext";
    [ThreadStatic] private static ISession _threadSession;

    // This constructor should be kept, otherwise NHibernate will fail to create an instance of this class.
    public HybridWebSessionContext(ISessionFactoryImplementor factory)
    {
    }

    protected override ISession Session
    {
        get
        {
            var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
            if (currentContext != null)
            {
                var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
                var session = items[_itemsKey] as ISession;
                if (session != null)
                {
                    return session;
                }
            }

            return _threadSession;
        }
        set
        {
            var currentContext = ReflectiveHttpContext.HttpContextCurrentGetter();
            if (currentContext != null)
            {
                var items = ReflectiveHttpContext.HttpContextItemsGetter(currentContext);
                items[_itemsKey] = value;
                return;
            }

            _threadSession = value;
        }
    }
}
like image 67
Allrameest Avatar answered Oct 08 '22 23:10

Allrameest