【问题标题】:Strategy Pattern using Unity使用 Unity 的策略模式
【发布时间】:2017-01-03 15:56:53
【问题描述】:

我正在尝试通过 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 .不幸的是,一旦我必须在“构造函数”中注入依赖项,我就无法使用此解决方案

【问题讨论】:

标签: c# design-patterns dependency-injection unity-container strategy-pattern


【解决方案1】:

简短的回答是你不能
因为:
你对 Men 类所做的是你在做 Poor Man's Dependency Injection。如果您使用统一,则不需要创建穷人的依赖注入,这就是统一作为框架帮助您的原因。假设当您像

一样进行 构造函数注入 时,是否有多个类型作为参数
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

【讨论】:

    猜你喜欢
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    相关资源
    最近更新 更多