使用 Unity 的策略模式

Strategy Pattern using Unity

我正在尝试通过 Unity 依赖注入来使用策略模式,我有以下情况:

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();
   }
}

如何设置统一容器以将正确的名称注入正确的人?

示例:

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"

类似问题: Strategy Pattern and Dependency Injection using Unity .不幸的是,一旦我必须在 "constructor"

中注入依赖项,我就无法使用此解决方案

简短的回答是你不能
因为:
你对 Men class 做的是你在做 穷人的依赖注入。如果您使用 unity,则不需要创建穷人的依赖注入,这就是 unity 作为框架帮助您的原因。假设当你像

那样进行 构造函数注入 时,如果你有不止一种类型作为参数
public Men(IName name, IAnother another,IAnother2 another2)
  {
     _name = name;
     // too much stuff to do....
  }

你能做什么?你真的不想处理那个,所以这就是你可以使用 Unity 的原因。

您必须注册类型并根据类型名称解析它们。

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


然后

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"

您可以检查 article