I want to use IoD with a class that implements an interface and has constructors with parameters.
The interface:
public interface IUsefulClass
{
string InterestingInfo { get; set; }
string RelevantStuff { get; set; }
}
Two simple properties, nothing much to say about it.
The class:
public class UsefulClass : IUsefulClass
{
public string InterestingInfo { get; set; }
public string RelevantStuff { get; set; }
public UsefulClass()
{
}
public UsefulClass(string p_strInterestingInfo)
{
InterestingInfo = p_strInterestingInfo;
}
public UsefulClass (string p_strInterestingInfo, string p_strRelevantStuff)
{
InterestingInfo = p_strInterestingInfo;
RelevantStuff = p_strRelevantStuff;
}
}
It has several different constructors, each setting the properties in its own way.
The call from another class:
public void HereGoes()
{
IUnityContainer z_ucoContainer = new UnityContainer();
z_ucoContainer.RegisterType<IUsefulClass, UsefulClass>();
IUsefulClass z_objUsefulButEmpty = z_ucoContainer.Resolve<IUsefulClass>();
IUsefulClass z_objUsefulAndInteresting = z_ucoContainer.Resolve<IUsefulClass>(new ParameterOverride("p_strInterestingInfo", "This is interesting information"));
IUsefulClass z_objUsefulAndInterestingToo = z_ucoContainer.Resolve<IUsefulClass>(new ParameterOverride[] { new ParameterOverride("p_strInterestingInfo", "This is very interesting information") });
IUsefulClass z_objUsefulInterestingAndRelevant = z_ucoContainer.Resolve<IUsefulClass>(new ParameterOverride("p_strInterestingInfo", "This is quite interesting information"), new ParameterOverride("p_strRelevantStuff", "More relevant stuff here"));
IUsefulClass z_objUsefulInterestingAndRelevantAsWell = z_ucoContainer.Resolve<IUsefulClass>(new ParameterOverride[] { new ParameterOverride("p_strInterestingInfo", "This is possibly the most interesting information"), new ParameterOverride("p_strRelevantStuff", "Look for relevant stuff there") });
}
On testing and debugging, I find that all five variables have null
in both properties.
Debugging some more, it turns out that each Resolve()
calls the parameter-less constructor.
I tried removing said constructor (and the code line that sets z_objUsefulButEmpty
, naturally): I get a Unity.ResolutionFailedException with the message, "Resolution failed with error: Failed to select a constructor for RegMat_VM.Infrastructure.UsefulClass".
I've looked and looked (here and there among other places), but can't find what I've done wrong. How can I make it work right?