Cant resolve Constructor Injection with multiple Concrete types on same interface

Jul 8, 2014 at 2:45 PM
If i register a single interface against two different concrete objects, how do i resolve an injectable class using constructor injection?

    _unityContainer.RegisterType<IGreeting, Tom.Greetings>("tom");
     _unityContainer.RegisterType<IGreeting, Stacey.Greetings>("stacey");
Injectable Class
public class SayHi
    private IGreeting _greeting;

    public SayHi(IGreeting greeting)
        _greeting = greeting;

    public void AnnounceYourself()
Main Class
var sayHi = container.Resolve<SayHi>("tom");
This will not work. But if i were to have a single registration, the SayHi class will resolve just fine. How do i go about telling it which one to resolve? Note: When i register the types, they are in a separate Composition Root assembly, so it doesnt know about the SayHi class.
Jul 8, 2014 at 5:55 PM
I assume you are getting a Microsoft.Practices.Unity.ResolutionFailedException.

At registration time you can tell Unity which IGreeting you want to inject:
_unityContainer.RegisterType<SayHi>(new InjectionConstructor(new ResolvedParameter<IGreeting>("tom")));
However, based on your comments it sounds like this doesn't work for you. In that case you can use a ResolverOverride to tell Unity which type you want at resolution time. You can use a ParameterOverride to do this:
var sayHi = _unityContainer.Resolve<SayHi>(
    new ParameterOverride("greeting", new ResolvedParameter<IGreeting>("tom"))

The above just injects Tom's IGreeting for the SayHi class without affecting any other objects in the graph.

I really don't like hard coding parameter names. To avoid that you can use a DependencyOverride:
var sayHi = _unityContainer.Resolve<SayHi>(
    new DependencyOverride<IGreeting>(
        new ResolvedParameter<IGreeting>("stacey"))

If you want all occurrences of IGreeting in the object graph to be resolved as "stacey" then remove the OnType constraint.

Randy Levy
Enterprise Library support engineer
Support How-to
Jul 9, 2014 at 1:28 PM
thank you randy! I will give that a whirl. I appreciate the quick response :)