比方说,我有一个类取决于接口IFace
以及注入构造函数的其他几个依赖项(由...
描述)。我也有2个实现的接口IFace
。在UnityContainer中注册类型以使用其他命名注册来解析构造函数参数
class Impl1 : IFace {}
class Impl2 : IFace {}
class Std : IStd {
Std(IFace impl1, IOtherDependency otherDep, ...) { ... }
}
我要注册Impl1
作为默认的实现和注册Impl2
为名为执行其应注入某些类。
container.RegisterType<IFace, Impl1>();
container.RegisterType<IFace, Impl2>("impl2");
注册Std
这样会注入默认Impl1实现:
container.RegisterType<IStd, Std>(); // this would inject the default implementation Impl1
如何注册Std
有一个名为注射执行不诉诸手动调用Resolve()
?我能想出的最好的是这样的:
container.RegisterType<IStd, Std>(
new InjectionConstructor(new ResolvedParameter<IFace>("impl2"), typeof(IOtherDependency, ...)));
我不与上面的方法一样的是,我还需要指定其他所有构造函数的参数;当签名发生变化时,我需要调整注册,编译器不会提出问题(运行时异常被抛出),而智能感知在此处不起作用。
我想吃点什么是沿着线的东西:(该InjectNamedType
显然是由)
container.RegisterType<IStd, Std>(
InjectNamedType<IFace>(name: "impl2")); // this would tell Unity to look for registration of IFace with that name
正是我所需要的。谢谢! – Martin