Multiple Injection Constructors

Jun 26, 2013 at 8:11 PM
I sometimes run into a situation which requires me to write several InjectionConstructors that are essentially the same one (i.e. new InjectionConstructor(sameParam);)

Is it possible to declare one (i.e. var injectionContractor = new new InjectionConstructor(sameParam);

and then write code like this
_container.Resolve<IClass1, Class1>(injectionConstructor);
_container.Resolve<IClass2, Class2>(injectionConstructor);

Thanks in advance for your help.
Jun 27, 2013 at 4:50 AM
The code, as posted will not compile since the Resolve method does not take an InjectionConstructor but ResolverOverride.

You can reuse an InjectionConstructor instance when registering types:
    IUnityContainer container = new UnityContainer();

    InjectionConstructor injectionConstructor = new InjectionConstructor("ABC");

    container.RegisterType<IClass1, Class1>(injectionConstructor);
    container.RegisterType<IClass2, Class2>(injectionConstructor);

You can also reuse a ParameterOverride instance but the parameter name for each constructor would have to have the same name:
    public class Class1 : IClass1
    {
        public Class1(string val) { }
    }
    public class Class2 : IClass2
    {
        public Class2(string val) { }
    }

    IUnityContainer container = new UnityContainer();

    container.RegisterType<IClass1, Class1>();
    container.RegisterType<IClass2, Class2>();

    var parameterOverride = new ParameterOverride("val", "ABC");

    container.Resolve<IClass1>(parameterOverride);
    container.Resolve<IClass2>(parameterOverride);

If the parameter names are different you can use a DependencyOverride but then that dependency would be used for all objects of that type resolved to construct the object graph (this might give unexpected results if not careful):
    public class Class1 : IClass1
    {
        public Class1(string val) { }
    }
    public class Class2 : IClass2
    {
        public Class2(string anotherVal) { }
    }

    IUnityContainer container = new UnityContainer();

    container.RegisterType<IClass1, Class1>();
    container.RegisterType<IClass2, Class2>();

    var dependencyOverride = new DependencyOverride(typeof(string), "ABC");

    container.Resolve<IClass1>(dependencyOverride);
    container.Resolve<IClass2>(dependencyOverride);

~~
Randy Levy
entlib.support@live.com
Enterprise Library support engineer
Support How-to
Marked as answer by randylevy on 10/12/2013 at 11:03 PM
Jun 27, 2013 at 2:36 PM
Thank you very much for your quick and thorough answer. I did mean to write RegisterType and not Resolve (brain fart), so your first answer is exactly what I needed to know. The other two options, while not applicable on this project (I'm using a ViewModelResolver and not actually making calls to "Resolve"), is very interesting. I did not know that those were possible. I will definitely keep those in mind for the future.

Thanks again for all your help.