try
{
// exception - instance has been disposed with container
example.SayHello();
}
catch (ObjectDisposedException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
ExternallyControlledLifetimeManager
ExternallyControlledLifetimeManager中的对象实例的生存期限将有UnityContainer外部的实现控制。此生存期管理器内部直存储了所提供对象实例的一个WeakReference。所以如果UnityContainer容器外部实现中没有对该对象实例的强引用,则该对象实例将被GC回收。再次请求该对象类型实例时,将会创建新的对象实例。
复制代码 代码如下:
private static void TestExternallyControlledLifetimeManager()
{
IExample example;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(IExample), typeof(Example),
new ExternallyControlledLifetimeManager());
// same instance is used in following
container.Resolve<IExample>().SayHello();
container.Resolve<IExample>().SayHello();
// run garbate collector. Stored Example instance will be released
// beacuse there is no reference for it and LifetimeManager holds
// only WeakReference
GC.Collect();
// object stored targeted by WeakReference was released
// new instance is created!
container.Resolve<IExample>().SayHello();
example = container.Resolve<IExample>();
}
example.SayHello();
Console.ReadKey();
}
这个结果证明强引用还存在,不知道为什么?如果你找到了原因,烦请告诉我,谢谢。
PerThreadLifetimeManager
PerThreadLifetimeManager模型提供“每线程单实例”功能。所有的对象实例在内部被存储在ThreadStatic的集合。容器并不跟踪对象实例的创建并且也不负责Dipose。
复制代码 代码如下:
private static void TestPerThreadLifetimeManager()
{
IExample example;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(IExample), typeof(Example),
new PerThreadLifetimeManager());
Action<int> action = delegate(int sleep)
{
// both calls use same instance per thread
container.Resolve<IExample>().SayHello();
Thread.Sleep(sleep);
container.Resolve<IExample>().SayHello();
};
Thread thread1 = new Thread((a) => action.Invoke((int)a));
Thread thread2 = new Thread((a) => action.Invoke((int)a));
thread1.Start(50);
thread2.Start(50);
thread1.Join();
thread2.Join();
example = container.Resolve<IExample>();
}
example.SayHello();
Console.ReadKey();
}
PerResolveLifetimeManager