Nhibernate session management strategy for a web application with workers in the background?

advertisements

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?


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