Diving Deep with Dependency Injection

Last updated 136 days ago by Ng Newsletter


One of the coolest features of AngularJS is an often-misunderstood and somewhat widely undervalued component of the framework. It is a crucial component of the framework that allows the rest of the framework to work seamlessly and efficiently. Dependency injection is what gives Angular its superpowers.

Dependency injection in Angular is what allows us to write our Angular code without worrying about the order in which our code is loaded. It allows us to use the same syntax across Angular components and not concern ourselves with how dependencies arrive. It gives us the ability to write tests efficiently and not worry about how to separate production components from those in testing.

What is Dependency Injection?

Dependency injection is nothing new. It’s a software design pattern that allows us to remove hard-coded dependencies and allows us to change defined dependencies at either compile time or run time.

For almost every line of code we’ll ever write ever in any language, it’s likely that we’ll need to depend upon someone else’s code. These libraries are called dependencies (because we depend upon them for our code to run properly).

For instance, we would not write a printf method when writing in c. It is already defined for us in the libc library, thus we have created a dependency on the libc library.

At run time, our code needs to know how to find the dependencies on which we’re basing our functionality. There are only so many ways that our code can get a hold of these dependencies. Either:

  • we tell our code how to look up the dependency from a global level
  • we pass the dependencies at run time to our objects

The first approach requires us to maintain a global lookup table for our objects to look up dependencies. That is, when our code is running, it is the responsibility of our object to look up how to get its dependencies.

When using a library like jQuery, our browser holds onto the global jQuery object that is often referred to by the $ symbol. Although it doesn’t seem like we are looking for the dependency, the browser is handling looking up the object for us.

Read full Article