I create a class that applies to dependency inversion principle, and used the dependency injection pattern, as follows:
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; }
}
So if I want to use BlackAndWhitePrinter
, I simply create an instance object and give it to my Print class with construction as follows:
ITypeOfPrinter typeofprinter = new BlackAndWhitePrinter();
Print hp = new Print(typeofprinter);
hp.print();
So Why I have to use Unity or another IoC framework here? I already did what I want as above:
var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, BlackAndWhitePrinter>();
var print = unityContainer.Resolve<Print>();
string colorfullText = print.print();