I want to write a class library that works in ASP.NET and standalone applications. Some differences in behavior are needed when running under ASP.NET. What is the recommended way to check if the library is running in an ASP.NET application?
I can check HttpContext.Current, as it appears to reliably return null when not running under ASP.NET. However, when running on a background thread in ASP.NET, it also returns null.
Any opinions on HttpContext.Current or other solutions?
ADDED: Thanks for all the advice on how to achieve a separation of concerns. However, I would like to add that this library will not be for general-purpose use, so for my particular case I do not need a lot of flexibility. In my mind, the best so far (not mentioned in this thread) is to check the HttpRuntime.AppDomainAppId static for null as it seems to work okay even for ASP.NET background threads. However, the various solutions contributed here will surely be helpful to others with more general needs.
I would push all the code common to both ASP.NET and desktop applications into a core library and test this, then create libraries that sit above the core application to provide deployment specifics – your HttpContext calls for example. You can then test reliably in both scenarios, knowing you only have to test the core application block once.
With regards checking HttpContext from a background thread – this doesn’t make sense and will always return null because HttpContext is defined by the asp.net request processor. If your code starts a background thread, HttpContext will be null in the new thread. Sorry about that 🙂
As a work around you could try adding each new session to a global collection
and then call into the collection from the background thread. You’d need to be careful about synchronising access to your session collection though..