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();
Dependency Injection as a pattern helps making your application code more maintainable. DI frameworks (a.k.a. IoC containers) can help making the Composition Root more maintainable.
But, if a IoC container doesn't help making your Composition Root more maintainable, don't use it in that scenario! That doesn't mean however that you shouldn't use Dependency Injection or other patterns and principles that help making your software more maintainable. You should whatever it takes to lower the total cost of ownership of the software you are building.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With