Singleton Per Call Context (Web Request) in Unity

Neat solution, but each instance of LifetimeManager should use a unique key rather than a constant:

private string _key = string.Format("PerCallContextLifeTimeManager_{0}", Guid.NewGuid());

Otherwise if you have more than one object registered with PerCallContextLifeTimeManager, they’re sharing the same key to access CallContext, and you won’t get your expected object back.

Also worth implementing RemoveValue to ensure objects are cleaned up:

public override void RemoveValue()
{
     CallContext.FreeNamedDataSlot(_key);
}

Leave a Comment