What is Dependency Injection?

Milecia - Nov 1 '18 - - Dev Community

There's too much jargon in the web development world. It's honestly surprising that we even understand each other. (do we really though?) That's why I'm going to tell you about dependency injection and what it really is. Let's get straight to it.

The core of dependency injection, the reason we do it at all, is to make a static map of service objects. Service objects are usually only built once when your application starts. The key is that some services depend on each other and the way they are used might change based on any environment conditions or configurations. So how do you use it?

Dependency injection is basically passing parameters to a function. It really is that simple. The reason that we like to do this is so we can keep a separation of responsibilities in the code. Are you surprised? It's not a framework and it doesn't have to be anything fancy. You can do dependency injection using constructors or a setter method.

You go into your service class and you want to make a new method. Normally you would leave the parameters empty and write all of your code and the objects you need to work with inside. When you are doing dependency injection, that means you pass in any objects you'll work with and use it instead of creating a local one.

What this does is it gives you the ability to use different objects in your method without having to rewrite any code. Once you start testing your code, dependency injection becomes incredible because you can pass in test objects without changing anything!

This is kind of what it looks like:

dependency injection

That purple box could be any object you want. The beautiful thing about this is you can process your before you use it. So if you need to clean it up or move some stuff around you can do that beforehand.

I hope that made some sense of dependency injection! It's not very complicated and it can and will help a lot with testing. Have you ever used Spring to handle your dependency injections? I'd like to hear if you liked it or not.


Hey! You should follow me on Twitter because reasons: https://twitter.com/FlippedCoding

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player