DryIoc - 使用构造函数注入时指定依赖关系
DryIoc - specifying dependency when using constructor injection
如果我注册同一个合约的两个实现,则使用 DryIoc - 如何在使用构造函数注入时控制使用哪个实现?
我知道你可以用密钥或元数据注册 - 是否有可能(使用属性?)来控制注入的实现?或者我应该需要一个集合并在 ctor 中找出正确的实现?
您可以通过 Made.Of 强类型规范指定在构造函数中使用的依赖项,如下所示:
container.Register<SomeClient>(Made.Of(
() => new SomeClient(Arg.Of<IDep>("service key of impl")));
这里是 有更多选项。
通过MEF Attributed Model支持属性注册:
[Export]
public class SomeClient {
public SomeClient([Import("x")]IDep dep) {}
}
[Export("x", typeof(IDep))]
public class X : IDep {}
[Export("y", typeof(IDep))]
public class Y : IDep {}
// in composition root:
using DryIoc.MefAttributedModel;
container = new Container().WithMefAttributedModel();
container.RegisterExports(
typeof(SomeClient),
typeof(X),
typeof(Y));
container.Resolve<SomeClient>(); // will inject X
如果我注册同一个合约的两个实现,则使用 DryIoc - 如何在使用构造函数注入时控制使用哪个实现?
我知道你可以用密钥或元数据注册 - 是否有可能(使用属性?)来控制注入的实现?或者我应该需要一个集合并在 ctor 中找出正确的实现?
您可以通过 Made.Of 强类型规范指定在构造函数中使用的依赖项,如下所示:
container.Register<SomeClient>(Made.Of(
() => new SomeClient(Arg.Of<IDep>("service key of impl")));
这里是
通过MEF Attributed Model支持属性注册:
[Export]
public class SomeClient {
public SomeClient([Import("x")]IDep dep) {}
}
[Export("x", typeof(IDep))]
public class X : IDep {}
[Export("y", typeof(IDep))]
public class Y : IDep {}
// in composition root:
using DryIoc.MefAttributedModel;
container = new Container().WithMefAttributedModel();
container.RegisterExports(
typeof(SomeClient),
typeof(X),
typeof(Y));
container.Resolve<SomeClient>(); // will inject X