CallContext isn't the greatest thing since sliced bread

In ASP.NET, it is quite common to need to store information in the context of a single web request. For example, a NHibernate session should usually exist for one web request. HttpContext is the tool for accomplishing this.

But what happens when you have code embedded in business logic that might not always be running in an ASP.NET web application? HttpContext isn’t valid, so you can’t use it. Why not use CallContext, since HttpContext uses this anyways?

I was starting to convert some of my code to use this, when I found this article. Apparently doing this works most of the time but can cause some nasty bugs since ASP.NET can switch HttpContext’s without switching CallContext’s.

Instead, code that could be called from ASP.NET and other applications should first check for context.

if(HttpContext.Current == null)
{
     //Using CallContext example since not in ASP.NET
     CallContext.SetData("blah", new object());
     object contextData = CallContext.GetData("blah");
}
else
{
     //Using HttpContext example since in ASP.NET
     HttpContext.Current.Items.Add("blah", new object());
     object contextData = HttpContext.Current.Items["blah"];
}

In fact, I will probably end up writing a static class to implement this so code doesn’t have to constantly check whether or not in an ASP.NET session.