I need help with this. I\'m using Unity as my container and I want to inject two different instances of the same type into my constructor.
class Example
{
There are many ways to achieve the results you want (as evidenced by the multiple answers). Here is another way using named registrations (without attributes):
IUnityContainer container = new UnityContainer();
container.RegisterType("ReceiveQueue",
new InjectionConstructor("receivePath"));
container.RegisterType("SendQueue",
new InjectionConstructor("sendPath"));
container.RegisterType(
new InjectionConstructor(
new ResolvedParameter("ReceiveQueue"),
new ResolvedParameter("SendQueue")));
Example example = container.Resolve();
The downside of this approach is that if the Example constructor is changed then the registration code must also be modified to match. Also, the error would be a runtime error and not a more preferable compile time error.
You could combine the above with an InjectionFactory to invoke the constructor manually to give compile time checking:
IUnityContainer container = new UnityContainer();
container.RegisterType("ReceiveQueue",
new InjectionConstructor("receivePath"));
container.RegisterType("SendQueue",
new InjectionConstructor("sendPath"));
container.RegisterType(new InjectionFactory(c =>
new Example(c.Resolve("ReceiveQueue"),
c.Resolve("SendQueue"))));
Example example = container.Resolve();
If you are using a composition root then the use of the magic strings ("ReceiveQueue" and "SendQueue") would be limited to the one registration location.