Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why I have to use IoC unity [duplicate]

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();
like image 204
Michael Riva Avatar asked Dec 12 '22 05:12

Michael Riva


1 Answers

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.

like image 68
Steven Avatar answered Dec 21 '22 22:12

Steven