Mic*_*iva 4 c# unit-testing design-patterns inversion-of-control unity-container
我创建了一个适用于依赖性反转原理的类,并使用了依赖注入模式,如下所示:
public interface ITypeOfPrinter
{
string Printing();
}
public class Print
{
private readonly ITypeOfPrinter _typeOfPrinter;
public Print(ITypeOfPrinter typeOfPrinter)
{
_typeOfPrinter = typeOfPrinter;
}
public string print()
{
return _typeOfPrinter.Printing();
}
}
public class BlackAndWhitePrinter : ITypeOfPrinter
{
public string Printing()
{
NumberOfPrints++;
return string.Format("it is Black and white printing {0}", NumberOfPrints);
}
public int NumberOfPrints { get; set; }
}
public class ColorfullPrinter : ITypeOfPrinter
{
public string Printing()
{
NumberOfPrints++;
return string.Format("it is colorfull printing {0}", NumberOfPrints);
}
public int NumberOfPrints { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我想使用BlackAndWhitePrinter
,我只需创建一个实例对象并将其提供给我的Print类,其构造如下:
ITypeOfPrinter typeofprinter = new BlackAndWhitePrinter();
Print hp = new Print(typeofprinter);
hp.print();
Run Code Online (Sandbox Code Playgroud)
那么为什么我必须在这里使用Unity或其他IoC框架?我已经做了我想要的如上所述:
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, BlackAndWhitePrinter>();
var print = unityContainer.Resolve<Print>();
string colorfullText = print.print();
Run Code Online (Sandbox Code Playgroud)
正如Steven的回答的附录一样,使用IOC框架有几个令人信服的理由,这些理由不适用于您提供的简单示例,但可以轻松应用于更复杂的应用程序; 但是我同意如果你觉得它没有带来好处,你实际上不必使用它.
典型的例子是ASP.NET
Controller
/ ApiController
.你永远不会自己实例化,ASP.NET
框架会为你做这件事.在这种情况下,如果您的控制器具有依赖关系,那么IOC框架允许您通过控制器上的接口轻松声明这些依赖关系,而不必担心它们是如何提供的.
这会使您的类分离,并允许更容易的单元测试,因为您可以模拟/存根依赖项.
new DeathStar(new NotAMoon(),
new PlanetExploder(),
new ExhaustPort(new CriticalVulnerabilityIgnorer()),
new StormTrooperGenerator(new DodgyBlasterGenerator(),
new HeadDoorBumper(new Ouch()),
new ShieldGenerator(new FurryCreatureVulnerability)),
new DramaticDuel(new Saber()), new DeadJedi()),
new DroidFactory(),
new TrashCompactor(new Monster()),
new Emperor(new Vader())
);
Run Code Online (Sandbox Code Playgroud)
不知道你,但我不想在我需要一个新的IDeathStar时输入它(更不用说尝试维护或调试它了) - 我更愿意说
var moon= IOCFrameworkOfChoice.Resolve<IDeathStar>();
Run Code Online (Sandbox Code Playgroud)
或者更现实地说:
public class MyController: Controller
{
public MyController(IDeathStar star)
{
//at runtime, at this point I have an armed and fully operational IDeathStar
//without having to worry about where it came from!
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
355 次 |
最近记录: |