我创建了一个符合依赖反转原则的类,并使用了依赖注入模式,代码如下:
那么为什么我要在这里使用Unity或其他IoC框架?我已经按照上述完成了我想要的内容。
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; }
}
如果我想要使用黑白打印机
,我只需要创建一个实例对象并将其作为构造函数的参数传递给我的打印类,具体如下:
ITypeOfPrinter typeofprinter = new BlackAndWhitePrinter();
Print hp = new Print(typeofprinter);
hp.print();
那么为什么我要在这里使用Unity或其他IoC框架?我已经按照上述完成了我想要的内容。
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, BlackAndWhitePrinter>();
var print = unityContainer.Resolve<Print>();
string colorfullText = print.print();