有很多方法可以实现您想要的结果(正如多个答案所证明的那样)。这是使用命名注册的另一种方法(没有属性):
IUnityContainer container = new UnityContainer();
container.RegisterType<IQueue, MessageQueue>("ReceiveQueue",
new InjectionConstructor("receivePath"));
container.RegisterType<IQueue, MessageQueue>("SendQueue",
new InjectionConstructor("sendPath"));
container.RegisterType<Example>(
new InjectionConstructor(
new ResolvedParameter<IQueue>("ReceiveQueue"),
new ResolvedParameter<IQueue>("SendQueue")));
Example example = container.Resolve<Example>();
这种方法的缺点是,如果示例构造函数发生更改,则还必须修改注册代码以匹配。此外,该错误将是运行时错误,而不是更可取的编译时错误。
您可以将上述内容与 InjectionFactory 结合起来,手动调用构造函数以进行编译时检查:
IUnityContainer container = new UnityContainer();
container.RegisterType<IQueue, MessageQueue>("ReceiveQueue",
new InjectionConstructor("receivePath"));
container.RegisterType<IQueue, MessageQueue>("SendQueue",
new InjectionConstructor("sendPath"));
container.RegisterType<Example>(new InjectionFactory(c =>
new Example(c.Resolve<IQueue>("ReceiveQueue"),
c.Resolve<IQueue>("SendQueue"))));
Example example = container.Resolve<Example>();
如果您使用组合根,那么魔术字符串(“ReceiveQueue”和“SendQueue”)的使用将仅限于一个注册位置。