PerThreadLifetimeManager Problems
When the built-in PerThreadLifetimeManager survival model of Unity is used, it is designed based on ThreadStatic TLS (Thread Local Storage). That is to say, for each managed ManagedThreadId, it caches the generated object instances.
Since CLR maintains the managed thread pool, the used threads will not be destroyed immediately and will continue to be reused as needed. Under conditions similar to ASP. NET PerCall or WCF PerCall, when Call1 is processed in thread ManagedThreadId1, Call2 occurs, and Call2 is likely to be processed in thread managedthreadid1. In this case, Call2 will automatically reuse the object instances generated and cached when processing call1.
If we want to generate a dedicated object instance for each call, PerThreadLifetimeManager is not suitable for this scenario.
There are two solutions:
1. continue to use the PerThreadLifetimeManager model. Instead of ThreadPool, manually create and destroy threads.
2. Custom object survival Model
PerCallContextLifeTimeManager
Copy codeThe Code is as follows:
Public class PerCallContextLifeTimeManager: LifetimeManager
{
Private string _ key =
String. Format (CultureInfo. InvariantCulture,
"PerCallContextLifeTimeManager _ {0}", Guid. NewGuid ());
Public override object GetValue ()
{
Return CallContext. GetData (_ key );
}
Public override void SetValue (object newValue)
{
CallContext. SetData (_ key, newValue );
}
Public override void RemoveValue ()
{
CallContext. FreeNamedDataSlot (_ key );
}
}
Example
Copy codeThe Code is as follows:
Private static void TestPerCallContextLifeTimeManager ()
{
IExample example;
Using (IUnityContainer container = new UnityContainer ())
{
Container. RegisterType (typeof (IExample), typeof (Example ),
New PerCallContextLifeTimeManager ());
Container. Resolve <IExample> (). SayHello ();
Container. Resolve <IExample> (). SayHello ();
Action <int> action = delegate (int sleep)
{
Container. Resolve <IExample> (). SayHello ();
Thread. Sleep (sleep );
Container. Resolve <IExample> (). SayHello ();
};
Thread thread1 = new Thread (a) => action. Invoke (int) ));
Thread thread2 = new Thread (a) => action. Invoke (int) ));
Thread1.Start (50 );
Thread2.Start (55 );
Thread1.Join ();
Thread2.Join ();
ThreadPool. QueueUserWorkItem (a) => action. Invoke (int) a), 50 );
ThreadPool. QueueUserWorkItem (a) => action. Invoke (int) a), 55 );
Thread. Sleep (100 );
ThreadPool. QueueUserWorkItem (a) => action. Invoke (int) a), 50 );
ThreadPool. QueueUserWorkItem (a) => action. Invoke (int) a), 55 );
Thread. Sleep (100 );
ThreadPool. QueueUserWorkItem (a) => action. Invoke (int) a), 50 );
ThreadPool. QueueUserWorkItem (a) => action. Invoke (int) a), 55 );
Thread. Sleep (100 );
Example = container. Resolve <IExample> ();
}
Example. SayHello ();
Console. ReadKey ();
}