【问题标题】:How set UnityContainer.Resolve<IType>() types precedence?如何设置 UnityContainer.Resolve<IType>() 类型优先级?
【发布时间】:2014-07-27 13:05:58
【问题描述】:

如何在UnityContainer 中设置优先级?例如,如何告诉Unity 我想将IVehicle 解析为Bus,而不是以下示例中的Car

var parent = new UnityContainer();
parent.RegisterType<IVehicle, Car>();
/*
...
*/
var child = parent.CreateChildContainer();

child.RegisterType<IVehicle, Bus>();

// now I want to get Bus, not Car:
var hopefullyBus = child.Resolve<IVehicle>();

【问题讨论】:

  • IIRC 这个例子应该可以正常工作,你试过了吗?
  • @Lukazoid,我的错... :-( 它工作正常...发布一个答案,以便我可以接受它
  • 我现在已经完成了,还有其他一些可供您选择的选项

标签: c# unity-container ioc-container


【解决方案1】:

正如您的示例当前,它应该可以工作,这是因为您正在向子容器添加类型注册,然后您将使用该子容器来执行实例的解析,这会导致 Bus

如果您希望使用单个 UnityContainer 实例,您有两种选择:

一种是将&lt;IVehicle, Bus&gt;的新类型映射添加到父级并在此之后执行解析,这将覆盖之前的&lt;IVehicle, Car&gt;类型映射。

另一种选择是使用命名注册并使用其中一个命名注册进行解析,即

parent.RegisterType<IVehicle, Car>("car");
parent.RegisterType<IVehicle, Bus>("bus");

// Notice the strings being used match the registrations
var bus = parent.Resolve<IVehicle>("bus"); 
var car = parent.Resolve<IVehicle>("car");

【讨论】:

  • 谢谢,不知道名称字符串。
猜你喜欢
  • 1970-01-01
  • 2011-05-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多