A few days ago, I had an issue with ASP.Net threading. I wanted to have a singleton object per web request. I actually need this for my unit of work. I wanted to instantiate
While this is fine calling this PerCallContextLifeTimeManager, I'm pretty sure this is not "safe" to be considered an ASP.Net Per-request LifeTimeManager.
If ASP.Net does its thread-swap then the only thing taken across to the new thread through CallContext is the current HttpContext - anything else you store in CallContext will be gone. This means under heavy load the code above could have unintended results - and I imagine it would be a real pain to track down why!
The only "safe" way to do this is with HttpContext.Current.Items, or doing something like:
public class PerCallContextOrRequestLifeTimeManager : LifetimeManager
{
private string _key = string.Format("PerCallContextOrRequestLifeTimeManager_{0}", Guid.NewGuid());
public override object GetValue()
{
if(HttpContext.Current != null)
return GetFromHttpContext();
else
return GetFromCallContext();
}
public override void SetValue(object newValue)
{
if(HttpContext.Current != null)
return SetInHttpContext();
else
return SetInCallContext();
}
public override void RemoveValue()
{
}
}
This obviously means taking dependencies on System.Web :-(
Much more information on this available at:
http://piers7.blogspot.com/2005/11/threadstatic-callcontext-and_02.html