有人可以解释以下示例代码的结果。问题是为什么ThreadContext中已解析的线程ID与当前托管线程ID不匹配?是否在所有托管线程之间缓存和共享了InjectionFactory的结果,即使我使用PerThreadLifetimeManager来为每个线程本地缓存委托结果。
public class ThreadContext
{
public ThreadContext(int id)
{
ThreadId = id;
}
public int ThreadId { get; set; }
}
static void Main(string[] args)
{
UnityContainer container = new UnityContainer();
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(() => DoWork(container));
}
Console.ReadLine();
}
private static void DoWork(IUnityContainer container)
{
int id = System.Threading.Thread.CurrentThread.ManagedThreadId;
container.RegisterType<ThreadContext>(new PerThreadLifetimeManager(), new InjectionFactory(_ => new ThreadContext(id)));
Console.WriteLine(id + " -- The current thread id is = " + container.Resolve<ThreadContext>().ThreadId);
}
}
提前致谢 / Arash的