I know this thread is fairly old at this point, but I figured I'd chime in with my thoughts on this. The TL;DR is that due to the untyped, dynamic nature of JavaScript, you can actually do quite a lot without resorting to the dependency injection (DI) pattern or using a DI framework. However, as an application grows larger and more complex, DI can definitely help the maintainability of your code.
DI in C#
To understand why DI isn't as big of a need in JavaScript, it's helpful to look at a strongly typed language like C#. (Apologies to those who don't know C#, but it should be easy enough to follow.) Say we have an app that describes a car and its horn. You would define two classes:
class Horn
{
public void Honk()
{
Console.WriteLine("beep!");
}
}
class Car
{
private Horn horn;
public Car()
{
this.horn = new Horn();
}
public void HonkHorn()
{
this.horn.Honk();
}
}
class Program
{
static void Main()
{
var car = new Car();
car.HonkHorn();
}
}
There are few issues with writing the code this way.
- The
Car
class is tightly coupled to the particular implementation of the horn in the Horn
class. If we want to change the type of horn used by the car, we have to modify the Car
class even though its usage of the horn doesn't change. This also makes testing difficult because we can't test the Car
class in isolation from its dependency, the Horn
class.
- The
Car
class is responsible for the lifecycle of the Horn
class. In a simple example like this it's not a big issue, but in real applications dependencies will have dependencies, which will have dependencies, etc. The Car
class would need to be responsible for creating the entire tree of its dependencies. This is not only complicated and repetitive, but it violates the "single responsibility" of the class. It should focus on being a car, not creating instances.
- There is no way to reuse the same dependency instances. Again, this isn't important in this toy application, but consider a database connection. You would typically have a single instance that is shared across your application.
Now, let's refactor this to use a dependency injection pattern.
interface IHorn
{
void Honk();
}
class Horn : IHorn
{
public void Honk()
{
Console.WriteLine("beep!");
}
}
class Car
{
private IHorn horn;
public Car(IHorn horn)
{
this.horn = horn;
}
public void HonkHorn()
{
this.horn.Honk();
}
}
class Program
{
static void Main()
{
var horn = new Horn();
var car = new Car(horn);
car.HonkHorn();
}
}
We've done two key things here. First, we've introduced an interface that our Horn
class implements. This lets us code the Car
class to the interface instead of the particular implementation. Now the code could take anything that implements IHorn
. Second, we've taken the horn instantiation out of Car
and passed it in instead. This resolves the issues above and leaves it to the application's main function to manage the specific instances and their lifecycles.
What this means is that we could introduce a new type of horn for the car to use without touching the Car
class:
class FrenchHorn : IHorn
{
public void Honk()
{
Console.WriteLine("le beep!");
}
}
The main could just inject an instance of the FrenchHorn
class instead. This also dramatically simplifies testing. You could create a MockHorn
class to inject into the Car
constructor to ensure you are testing just the Car
class in isolation.
The example above shows manual dependency injection. Typically DI is done with a framework (e.g. Unity or Ninject in the C# world). These frameworks will do all of the dependency wiring for you by walking your dependency graph and creating instances as needed.
The Standard Node.js Way
Now let's look at the same example in Node.js. We would probably break our code into 3 modules:
// horn.js
module.exports = {
honk: function () {
console.log("beep!");
}
};
// car.js
var horn = require("./horn");
module.exports = {
honkHorn: function () {
horn.honk();
}
};
// index.js
var car = require("./car");
car.honkHorn();
Because JavaScript is untyped, we don't have quite the same tight coupling that we had before. There is no need for interfaces (nor do they exist) as the car
module will just attempt to call the honk
method on whatever the horn
module exports.
Additionally, because Node's require
caches everything, modules are essentially singletons stored in a container. Any other module that performs a require
on the horn
module will get the exact same instance. This makes sharing singleton objects like database connections very easy.
Now there is still the issue that the car
module is responsible for fetching its own dependency horn
. If you wanted the car to use a different module for its horn, you'd have to change the require
statement in the car
module. This is not a very common thing to do, but it does cause issues with testing.
The usual way people handle the testing problem is with proxyquire. Owing to the dynamic nature of JavaScript, proxyquire intercepts calls to require and returns any stubs/mocks you provide instead.
var proxyquire = require('proxyquire');
var hornStub = {
honk: function () {
console.log("test beep!");
}
};
var car = proxyquire('./car', { './horn': hornStub });
// Now make test assertions on car...
This is more than enough for most applications. If it works for your app then go with it. However, in my experience as applications grow larger and more complex, maintaining code like this becomes harder.
DI in JavaScript
Node.js is very flexible. If you aren't satisfied with the method above, you can write your modules using the dependency injection pattern. In this pattern, every module exports a factory function (or a class constructor).
// horn.js
module.exports = function () {
return {
honk: function () {
console.log("beep!");
}
};
};
// car.js
module.exports = function (horn) {
return {
honkHorn: function () {
horn.honk();
}
};
};
// index.js
var horn = require("./horn")();
var car = require("./car")(horn);
car.honkHorn();
This is very much analogous to the C# method earlier in that the index.js
module is responsible for instance lifecycles and wiring. Unit testing is quite simple as you can just pass in mocks/stubs to the functions. Again, if this is good enough for your application go with it.
Bolus DI Framework
Unlike C#, there are no established standard DI frameworks to help with your dependency management. There are a number of frameworks in the npm registry but none have widespread adoption. Many of these options have been cited already in the other answers.
I wasn't particularly happy with any of the options available so I wrote my own called bolus. Bolus is designed to work with code written in the DI style above and tries to be very DRY and very simple. Using the exact same car.js
and horn.js
modules above, you can rewrite the index.js
module with bolus as:
// index.js
var Injector = require("bolus");
var injector = new Injector();
injector.registerPath("**/*.js");
var car = injector.resolve("car");
car.honkHorn();
The basic idea is that you create an injector. You register all of your modules in the injector. Then you simply resolve what you need. Bolus will walk the dependency graph and create and inject dependencies as needed. You don't save much in a toy example like this, but in large applications with complicated dependency trees the savings are huge.
Bolus supports a bunch of nifty features like optional dependencies and test globals, but there are two key benefits I've seen relative to the standard Node.js approach. First, if you have a lot of similar applications, you can create a private npm module for your base that creates an injector and registers useful objects on it. Then your specific apps can add, override, and resolve as needed much like how AngularJS's injector works. Second, you can use bolus to manage various contexts of dependencies. For example, you could use middleware to create a child injector per request, register the user id, session id, logger, etc. on the injector along with any modules depending on those. Then resolve what you need to serve requests. This gives you instances of your modules per request and prevents having to pass the logger, etc. along to every module function call.