Why should I use IoC unity

I create a class that applies to the 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; }
}

Therefore, if I want to use BlackAndWhitePrinter, I simply create an instance of the object and pass it to the Print class with the structure as follows:

ITypeOfPrinter typeofprinter = new BlackAndWhitePrinter();
Print hp = new Print(typeofprinter);
hp.print();

So why should I use Unity or another IoC framework? I already did what I wanted, as stated above:

var unityContainer = new UnityContainer();
unityContainer.RegisterType<ITypeOfPrinter, BlackAndWhitePrinter>();
var print = unityContainer.Resolve<Print>();
string colorfullText = print.print();
+4
source share
2 answers

, 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())
            );

, ( , ), IDeathStar -

var moon= IOCFrameworkOfChoice.Resolve<IDeathStar>();

:

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!
    }
}
+5

. DI ( IoC.a. IoC) .

IoC , ! , , Dependency Injection , . , , .

+7

Source: https://habr.com/ru/post/1541680/


All Articles