I'm trying to use the Strategy pattern using dependecy injection with Unity, and i have the following scenario:
public Interface IName
{
string WhatIsYourName()
}
public class John : IName
{
public string WhatIsYourName()
{
return "John";
}
}
public class Larry : IName
{
public string WhatIsYourName()
{
return "Larry";
}
}
public Interface IPerson
{
IntroduceYourself();
}
public class Men : IPerson
{
private IName _name;
public Men(IName name)
{
_name = name;
}
public string IntroduceYourself()
{
return "My name is " + _name.WhatIsYourName();
}
}
How can i set unity container to inject the correct name to the correct person?
Example:
IPerson_John = //code to container resolve
IPerson_John.IntroduceYouself(); // "My name is john"
IPerson_Larry = //code to container resolve
IPerson_Larry.IntroduceYouself(); // "My name is Larry"
Similar problem: Strategy Pattern and Dependency Injection using Unity . Unfortunately, I cannot use this solution once i have to inject dependecy in the "constructor"
Short answer is You cant.
Because:
What you are doing with Men class is you are making Poor Man's Dependency Injection. You dont need to create poor man's dependency injection if you are using unity, this is why unity helps you as a framework. Suppose if you have more than one type as parameters when you make constructor injection like
What you could do? You really dont wanna deal with that, so thats why you can use Unity.
You have to register type and resolve them according to type name.
And then
You can check that article