Try using named instances:
IUnityContainer container = new UnityContainer(); container.RegisterType<Type1>(); container.RegisterType<Type2>("Instance 1", new ContainerControlledLifetimeManager()); container.RegisterType<Type2>("Instance 2", new ContainerControlledLifetimeManager()); container.RegisterType<Type3>(); Type1 type1 = container.Resolve<Type1>(); if (type1 == ...) { Type2 instance1 = container.Resolve<Type2>("Instance 1"); } else { Type2 instance2 = ontainer.Resolve<Type2>("Instance 2"); }
IUnityContainer container = new UnityContainer(); container.RegisterType<Type1>(); container.RegisterType<Type2>("Instance 1", new ContainerControlledLifetimeManager()); container.RegisterType<Type2>("Instance 2", new ContainerControlledLifetimeManager()); container.RegisterType<Type3>(); Type1 type1 = container.Resolve<Type1>(); if (type1 == ...) { Type2 instance1 = container.Resolve<Type2>("Instance 1"); } else { Type2 instance2 = ontainer.Resolve<Type2>("Instance 2"); }
You can perform some type 1 checks and decide which type 2 instance you need. Note that the parameter "new ContainerControlledLifetimeManager ()" initializes an instance of a single type of the resistance type, so you always get the same instance of type 2.
Update: The same with interfaces. Hope this helps.
IUnityContainer container = new UnityContainer(); container.RegisterType<TextDocument>(); container.RegisterType<ImageDocument>(); container.RegisterType(typeof (IView), typeof (TextView), "Text", new ContainerControlledLifetimeManager()); container.RegisterType(typeof (IView), typeof (ImageView), "Image", new ContainerControlledLifetimeManager()); IDocument document = container.Resolve<TextDocument>(); IView view = null; if (document is TextDocument) { view = container.Resolve<IView>("Text"); } else { view = container.Resolve<IView>("Image"); } view.Show();
IUnityContainer container = new UnityContainer(); container.RegisterType<TextDocument>(); container.RegisterType<ImageDocument>(); container.RegisterType(typeof (IView), typeof (TextView), "Text", new ContainerControlledLifetimeManager()); container.RegisterType(typeof (IView), typeof (ImageView), "Image", new ContainerControlledLifetimeManager()); IDocument document = container.Resolve<TextDocument>(); IView view = null; if (document is TextDocument) { view = container.Resolve<IView>("Text"); } else { view = container.Resolve<IView>("Image"); } view.Show();
Alexander
source share