FatAlbert FatAlbert - 2 months ago 25x
C# Question

Resolve instance with multiple constructors using unity

I'd like to create an instance of a class using unity where the class has two constructors with the same number of parameters.

Here is the instantiation:

_unityContainer.Resolve<IGradeType>(new ParameterOverride("gradeTypeStringFromXmlFile", gradeTypeStringFromXmlFile));

And here are the constructors:

public GradeType( string gradeTypeStringFromXmlFile)
_gradeTypeStringFromXmlFile = gradeTypeStringFromXmlFile;

public GradeType(Enum.GradeType gradeType)
_gradeType = gradeType;

If I try to do this I get an exception saying The type GradeType has multiple constructors of length 1. Unable to disambiguate.

I can set the attribute [InjectionConstructor] over one constructor to make it work with one, but then I can't create an instance with unity using the other constructor.

Is it some way to have multiple constructors with equal number of parameters and still use unity to create the instances?


Yes it's possible to tell Unity which constructor should it use, but you can only do this when you register your type with InjectionConstructor. If you want to use both constructor it's even complicated because you have to name your registrations and use that name when resolving.

Sample built with Unity version 2.1.505:

var continer = new UnityContainer();

continer.RegisterType<IGradeType, GradeType>("stringConstructor", 
    new InjectionConstructor(typeof(string)));

continer.RegisterType<IGradeType, GradeType>("enumConstructor",
    new InjectionConstructor(typeof(EnumGradeType)));

IGradeType stringGradeType = continer.Resolve<IGradeType>("stringContructor" , 
    new DependencyOverride(typeof(string), "some string"));

IGradeType enumGradeType = continer.Resolve<IGradeType>("enumConstructor", 
    new DependencyOverride(typeof(EnumGradeType), EnumGradeType.Value));