【发布时间】: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 .不幸的是,一旦我必须在“构造函数”中注入依赖项,我就无法使用此解决方案
【问题讨论】:
-
我猜你可以使用泛型。 msdn.microsoft.com/en-us/en-en/library/d5x73970.aspx 这样你会以 IPerson_John = new Person
();但这并没有使用 Unity -
我认为你不应该对这些类使用 DI。更多详情请看这篇文章:misko.hevery.com/2008/09/30/to-new-or-not-to-new
标签: c# design-patterns dependency-injection unity-container strategy-pattern