DEV Community

Discussion on: Explain Dependency Injection (DI) like I am five.

Collapse
 
brandinchiu profile image
Brandin Chiu

Dependency injection is used to allow your application to share instances of specific classes instead of you having to instantiate and initialize them many times around your application.

How this happens will vary with each framework, but the goal is to relegate the management of your classes (typically things like service classes) to the framework instead of your application.

The framework will instantiate the class in question at runtime, and then your code will ask for it using an identifier somewhere instead of creating a new one. This way, everywhere in your code is always using the same instance of the class.

Tl;dr: dependency injection makes the framework instantiate classes for your application and shares them with other parts of your code instead of you needing to call new Foo() yourself. It helps reduce memory usage.

Collapse
 
tam360 profile image
Mirza

Are there any drawbacks of challenges associated with DI?

Collapse
 
brandinchiu profile image
Brandin Chiu

Depending on your school of thought, some people may not find the way you interact with your classes to be terribly intuitive, as you need to have a good understanding of the underlying management.

Also, depending on which framework you're using, it may be easier or more difficult to handle how the framework manages constructor arguments for the classes you need.

On the bright side though it makes unit tests simpler because it's very easy to stib/mock your services since you're never interacting with them directly.

Thread Thread
 
tam360 profile image
Mirza

I guess the main challenge of using DI is having a solid knowledge of interface/class's internal workings. Since DI does all the things behind the curtain, it becomes annoying when one starts using them without understanding. This I think is true in the case of debugging.

Thread Thread
 
brandinchiu profile image
Brandin Chiu

For sure.

I personally think the pros outweigh the cons, but to each their own.