ContainerControlledLifetimeManager将为UnityContainer及其子容器提供一个Singleton的注册类型对象实例。其只在第一次请求某注册类型时创建一个新的对象实例,该对象实例将被存储到生存期管理器中,并且一直被重用。当容器析构时,生存期管理器会调用RemoveValue将存储的对象销毁。
Singleton对象实例对应每个对象类型注册,如果同一对象类型注册多次,则将为每次注册创建单一的实例。
复制代码 代码如下:
private static void TestContainerControlledLifetimeManager()
{
IExample example;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(IExample), typeof(Example),
new ContainerControlledLifetimeManager());
IUnityContainer firstSub = null;
IUnityContainer secondSub = null;
try
{
firstSub = container.CreateChildContainer();
secondSub = container.CreateChildContainer();
// all containers share same instance
// each resolve returns same instance
firstSub.Resolve<IExample>().SayHello();
// run one resolving in other thread and still receive same instance
Thread thread = new Thread(
() => secondSub.Resolve<IExample>().SayHello());
thread.Start();
container.Resolve<IExample>().SayHello();
example = container.Resolve<IExample>();
thread.Join();
}
finally
{
if (firstSub != null) firstSub.Dispose();
if (secondSub != null) secondSub.Dispose();
}
}
try
{
// exception - instance has been disposed with container
example.SayHello();
}
catch (ObjectDisposedException ex)
{
Console.WriteLine(ex.Message);
}
Console.ReadKey();
}
HierarchicalLifetimeManager类衍生自ContainerControlledLifetimeManager,其继承了父类的所有行为。与父类的不同之处在于子容器中的生存期管理器行为。ContainerControlledLifetimeManager共享相同的对象实例,包括在子容器中。而HierarchicalLifetimeManager只在同一个容器内共享,每个子容器都有其单独的对象实例。
复制代码 代码如下:
private static void TestHierarchicalLifetimeManager()
{
IExample example;
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType(typeof(IExample), typeof(Example),
new HierarchicalLifetimeManager());
IUnityContainer firstSub = null;
IUnityContainer secondSub = null;
try
{
firstSub = container.CreateChildContainer();
secondSub = container.CreateChildContainer();
// each subcontainer has its own instance
firstSub.Resolve<IExample>().SayHello();
secondSub.Resolve<IExample>().SayHello();
container.Resolve<IExample>().SayHello();
example = firstSub.Resolve<IExample>();
}
finally
{
if (firstSub != null) firstSub.Dispose();
if (secondSub != null) secondSub.Dispose();
}
}