Skip to content

Instantly share code, notes, and snippets.

@coolaj86
Last active January 13, 2018 04:24
Show Gist options
  • Save coolaj86/1a384f21c91f8af78db1 to your computer and use it in GitHub Desktop.
Save coolaj86/1a384f21c91f8af78db1 to your computer and use it in GitHub Desktop.
Static vs Dynamic vs Automatic Dependency Injection
// It's known that I need arg1, arg2, arg3
function myThing(arg1, arg2, arg2) {
return arg1 + arg2 + arg3;
}
registerWithInjector(myThing);
// It's not known which things I need, so I specify
var myThing = ['foo', 'bar', 'baz', function (foo, bar, baz) {
return foo + bar + baz;
}]
registerWithInjector(myThing);
// There's black magic to figure out how to load which modules based on myThing.toString() introspection
function myThing($bar, $foo, $baz) {
return $foo + $bar + $baz;
}
registerWithInjector(myThing);

In AngularJS the term "Dependency Injection" gets thrown around a lot.

Many people understand it to mean "throw a dollar sign in front of variable and it pulls that module from the standard library, regardless of the order of the arguments". That's just because angular happens to use dependency injection behind-the-scenes, so they advertise that they use it, but that particular mechanic is just a mechanic (automatic constructor dependency injection in javascript), not the pattern.

Example:

because

function ($foo, $bar, $baz) {
 // ...
}

is the same as this

function ($bar, $baz, $foo) {
 // ...
}

people say "AH! dependency injection!"

FALSE: This is NOT Dependency Injection.

You can implement such a mechanic while completely ignoring the pattern dependency injection.

Dependency injection is a design pattern that could just as well be implemented with RequireJS and, with a little thinking, CommonJS meaning that instead of the module which needs 'foo', 'bar', and 'baz' getting them directly, it accepts them.

This Java example makes the concept more clear:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment