尝试使用命名实例:
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");
}
您可以对类型 1 进行一些检查并决定您需要哪个类型 2 的实例。请注意,“new ContainerControlledLifetimeManager()”参数将初始化被抵抗类型的单例实例,因此您将始终获得相同的类型 2 实例。
更新:与接口相同。希望这可以帮助。
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();