TypeScript
/Advanced
Dependency Injection (DI)
Definition
A design pattern in which a class receives its dependencies from external sources rather than creating them itself.
Explain Like I'm New
Imagine a `Car` class. A bad Car builds its own engine inside its constructor (`this.engine = new V8Engine()`). Now that Car is permanently stuck with a V8 engine. Dependency Injection says: 'Don't build the engine. Ask for the engine in the constructor arguments.' (`constructor(engine: IEngine)`). Now you can easily pass in an ElectricEngine or a V8Engine.
Real World Example
Angular and NestJS are built entirely around DI. When you ask for a `DatabaseService` in a controller's constructor, the framework automatically finds it and injects it for you (Inversion of Control).
Common Use Cases
- •Highly testable architectures
- •Large scale frameworks (Angular/NestJS)
Interactive Example
Loading Code Playground...
Interview Questions
basic
- What is a 'Dependency' in programming?
intermediate
- How does DI make unit testing easier?
advanced
- What is an IoC (Inversion of Control) Container?