What is dependency injection?

Why Interviewers Ask This

Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for SOLID Principles development. It reveals whether you understand the building blocks that more complex concepts rely on.

Answer

Dependency Injection (DI) is a technique where a class receives its dependencies from an external source rather than creating them internally. Instead of class Service { private db = new Database(); }, the dependency is injected: class Service { constructor(private db: DatabaseInterface) {} }. There are three forms: Constructor injection (most common and recommended), setter injection (via setter methods), and interface injection. DI is the practical implementation of DIP — by injecting abstractions, you decouple the class from concrete implementations. DI containers (Spring in Java, Laravel's service container in PHP, NestJS IoC in Node.js) automate the wiring of dependencies across large applications.

Common Mistake

Rushing to answer is a common mistake. Take two seconds to structure your response: definition → example → trade-off. This structure makes complex SOLID Principles answers easy to follow.