Unity的Container允许树型的层次结构,比如一个Container下可以有多个子Container,这些Container下也允许有多个子Container。示例如下:
1 IUnityContainer unityContainer = new UnityContainer(); 2 IUnityContainer childUnityContainer = unityContainer.CreateChildContainer(); 3 4 unityContainer.RegisterType<TextWriter, StringWriter>(new ContainerControlledLifetimeManager(), new InjectionConstructor()); 5 childUnityContainer.RegisterType<TextWriter, StreamWriter>(new PerThreadLifetimeManager(), new InjectionConstructor(“a”)); 6 7 TextWriter textWriter = unityContainer.Resolve<TextWriter>(); 8 TextWriter textWriter2 = childUnityContainer.Resolve<TextWriter>();
值得注意的是一般情况下父Container的销毁并不影响子Container的使用。