# Patterns
# Dependency Injection
Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It's a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.
Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g. Spring, Inversify) to do that, but they certainly aren't required. You don't need those frameworks to have dependency injection. Instantiating and passing objects (dependencies) explicitly is just as good an injection as injection by framework.
Dependency injection is a very simple concept. Instead of this code:
class A {
private b: B;
constructor() {
this.b = new B(); // A *depends on* B
}
public DoSomeStuff() {
// Do something with B here
}
}
function main(args: string[]) {
const a: A = new A();
a.DoSomeStuff();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
You write code like this:
class A {
private b: B;
constructor(b: B) { // A now takes its dependencies as arguments
this.b = b; // no "new"!
}
public DoSomeStuff() {
// Do something with B here
}
}
function main(args: string[]) {
const b: B = new B(); // B is constructed here instead
const a: A = new A(b);
a.DoSomeStuff();
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
And that's it. This gives you a ton of advantages. Two important ones are the ability to control functionality from a central place (the main() function) instead of spreading it throughout your program, and the ability to more easily test each class in isolation (because you can pass mocks or other faked objects into its constructor instead of a real value).
The drawback, of course, is that you now have one mega-function that knows about all the classes used by your program. That's what DI frameworks can help with.
# Javascript
For Javascript and Typescript, one of the most famous DI frameworks is Inversify, to understand how it works, You can check their simple example demo: https://github.com/inversify/inversify-basic-example. And of course as usual, check inversify documentation.
And this article is also useful to follow to understand how to work with inversify.
# References
- Why should you use dependency injection
- Dependency Injection in TypeScript
- Inversify
- S.O.L.I.D: The First 5 Principles of Object Oriented Design
- Dependency injection in TypeScript applications powered by InversifyJS
- Implementing SOLID and the onion architecture in Node.js with TypeScript and InversifyJS
- Concept of Domain Driven Design
- Inversion of Control with Typescript and Inversify