14.4 StyletIoC Keys
到目前为止,我一直在说 StyletIoC 拥有service -> implementation type(s)
.
这实际上是一个小谎言。事实上,映射是[service, key] -> implementation type(s)
,其中key
是您提供的任意字符串。
这个键的概念允许你有,比方说,两个实现IVehicle
,但是需要一个的东西IVehicle
可以间接地指定它们在哪个实现之后。
有多种方法可以指定此密钥,无论是在创建注册时,还是在从 StyletIoC 请求服务实例时。
指定与类型关联的键
可以通过几种方式指定键。
您可以通过使用类型本身的属性来指定要与类型关联的键[Inject(Key = "mykey")]
,例如:
[Inject(Key = "old")]
class OldBanger : IVehicle {
... }
您也可以在绑定类型时指定它,使用WithKey
方法。这会覆盖属性中的键(如果有):
builder.Bind<IVehicle>().To<HotHatchback>().WithKey("new");
builder.Bind<IVehicle>().To(container => new OldBanger()).WithKey("old");
使用其键检索类型
所有不同的注入方法方法都支持在决定注入哪种类型时指定要使用的键。
使用 获取实例目录时IContainer.Get
,您可以传递要使用的密钥:
ioc.Get(“old”);
使用构造函数注入时,您可以使用属性指定键使用[Inject(Key = "key")
:
class CarOwner
{
// IVehicle will be a HotHatchback, as that was registered with the key "new"
public CarOwner([Inject(Key = "new") IVehicle vehicle) {
... }
}
同样,你可以在使用属性注入时使用[Inject(Key = "key")]
语法:
class CarOwner
{
[Inject(Key = "old")]
public IVehicle Vehicle {
get; set; }
}
键和集合(Keys and Collections)
您还可以将keys用于具有多个实现的服务,例如:
builder.Bind<IVehicle>().To<HotHatchback>().WithKey("new");
builder.Bind<IVehicle>().To<Roadster>().WithKey("new");
builder.Bind<IVehicle>().To<OldBanger>().WithKey("old");
// Then...
class NewCarGarage
{
public NewCarGarage([Inject("new")] IEnumerable<IVehicle> vehicles) {
... }
}
class OldCarGarage
{
public OldCarGarage([Inject("old")] IEnumerable<IVehicle> vehicles {
... }
}
/// Or...
var newVehicles = ioc.GetAll<IVehicle>("new");
项目原地址:https://github.com/canton7/Stylet
当前文档原地址:https://github.com/canton7/Stylet/wiki/StyletIoC-Keys
上一节:WPF的MVVM框架Stylet开发文档 14.3 StyletIoC注入
下一节:WPF的MVVM框架Stylet开发文档 14.5 StyletIoC 工厂
上一篇:WPF的MVVM框架Stylet开发文档 13.验证模型基类ValidatingModelBase
下一篇:WPF的MVVM框架Stylet开发文档 15. 视图管理器 The ViewManager