IoC containers, are they really necessary?

When using the principle of "Dependency Inversion", it is recommended to use embedding via the constructor, but ultimately, as the complexity of the application increases, the number of dependencies that need to be embedded increases. There is a huge class-God, which manages all these dependencies (this approach is also called poor man's DI "Dependency Injection in .NET").

Such code, at least, turns out to be testable, with the exception of the class that manages dependencies.

When using the IOC container, the same approach is actually obtained, so why use additional settings for containers and extra frameworks?

When using an IoC container, we can request the instance we need anywhere (pre-configured, of course), (https://habr.com/post/131993/):

// там где нужно создать экземпляр ScheduleViewer мы вместо new, делаем так:
ScheduleViewer scheduleViewer= ninjectKernel.Get<ScheduleViewer>();

And does this not increase the coherence of the code when we insert such requests everywhere on created instance? After all, then the code becomes practically non-testable (meaning unit testing)

Author: Aleksandr Necheukhin, 2018-10-14

1 answers

You are quite right that using ninjectKernel.Get<ScheduleViewer>() instead of new ScheduleViewer() is not a good idea. But DI is not reduced to constant ninjectKernel.Get, it is an anti-pattern.

Instead of constantly accessing the IoC container, you need to request all your dependencies as constructor parameters.:

class Foo 
{
    private readonly ScheduleViewer viewer;
    public Foo(ScheduleViewer viewer)
    {
        this.viewer = viewer;
    }
}

If you want to create new objects, you should request their factory:

class Foo 
{
    private readonly Func<ScheduleViewer> viewerFactory;
    public Foo(Func<ScheduleViewer> viewerFactory)
    {
        this.viewerFactory = viewerFactory;
    }
}
 3
Author: Pavel Mayorov, 2018-10-14 15:22:34