DelegatingHandler access to HttpContext.Current

Topics: Web Api
Sep 22, 2011 at 4:13 PM

We are using NHibernate for our DAL and we store the session in HttpContext.Current.Items using S#arpArchitecture's WebSessionStorage. See this SO post: http://stackoverflow.com/questions/6527545/using-sharparchitectures-nhibernatesession-in-conjunction-with-a-different-threa. Due the the asynchronous nature of delegating handlers, they often execute on a different thread from the one that started handling the request in Application_BeginRequest in Global.asax and therefore HttpContext.Current is null for these threads.

I don't quite like the accepted answer on the SO post because a "HybridWebSessionStorage" just feels wrong and I don't like the idea that for a particular request, you may be working with more than one type of session storage. Also, due to the way that WebSessionStorage automatically closes the NHibernate session(s) on Application_EndRequest, I'm a little paranoid that sessions that are created in ThreadLocalStorage will be closed before the thread(s) that are using them have finished their work.

Am I being paranoid here? Can I be sure that the asynchronous operations will always be completed before Application_EndRequest is fired? Or are there any plans to allow for synchronous DelegatingHandlers?