1

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"

Community
  • 1
  • 1
Mario Guadagnin
  • 476
  • 7
  • 17
  • you could use generics i guess. https://msdn.microsoft.com/en-us/en-en/library/d5x73970.aspx This way you would end with IPerson_John = new Person(); But that makes no use of Unity – yan yankelevich Jan 03 '17 at 16:33
  • I don't think that you should use DI for these classes. See this article for more details: http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/ – Yacoub Massad Jan 03 '17 at 17:18

1 Answers1

1

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

public Men(IName name, IAnother another,IAnother2 another2)
  {
     _name = name;
     // too much stuff to do....
  }

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.

container.RegisterType<IName, Larry>("Larry");
container.RegisterType<IName, John>("John");


And then

IName IPerson_John=container.Resolve<IName>("John");
IPerson_John.IntroduceYouself(); // "My name is john"

IName IPerson_Larry= container.Resolve<IName>("Larry");
IPerson_Larry.IntroduceYouself(); // "My name is Larry"

You can check that article

Mustafa Ekici
  • 7,263
  • 9
  • 55
  • 75