Dependency Injection is a set of software design principles and patterns that enables you to reduce coupling between components
Dependency injection (DI) is a set of software design-principles and design-patterns for object-oriented programming (oop) involving dynamically injecting (inserting) into a software component dependencies (service components) that it needs to function, without needing the dependent component to hard-code a dependency on the service. This reduces coupling between the dependent consumer and the service.
Benefits of Dependency Injection
- Separation of concerns.
- Boilerplate-code reduction in application classes because all work to initialize dependencies is handled by the composer.
- Configurable components makes application easily extendable.
- Unit testing is easy with mock objects.
Disadvantages of Dependency Injection
- If overused, it can lead to maintenance issues because effect of changes are known at runtime.
- Dependency injection hides the service class dependencies that can lead to runtime errors that would have been caught at compile time.
Background questions
If you need a general introduction to DI, see: What is dependency injection?
If you need a non-technical introduction, see: How to explain Dependency Injection to a 5-year old.
If you would like to understand the relationship between DI and inversion-of-control (IoC), see: Inversion of Control < Dependency Injection.
For general recommendations for writing DI-friendly code without a DI Container, see: Dependency Inject (DI) “friendly” library.
If you are wondering why you should use a DI Container (a.k.a. an ioc-container) instead creating classes using the
new
keyword of your language, see: Why do I need an IoC Container as opposed to straightforward DI code?.If you are wondering what the Composition Root is, see: What is a composition root in the context of Dependency Injection.
For potential downsides of using DI, see: What are the downsides to using dependency injection?
Dependency injection and Inversion of Control are closely related. To understand the difference, see: where-exactly-is-the-difference-between-ioc-and-di.
Resources / books
The following list of books (in print) focus specifically on Dependency Injection.
- Android Dependency Injection Using Dagger - Eng Mahmoud Ramadan [2020]
- Dependency Injection, Principles, Practices, and Patterns - Mark Seemann, et al. [2019]
- Hands-On Dependency Injection in Go - Corey Scott [2018]
- Java 9 Dependency Injection - Krunal Patel, et al. [2018]
- Dependency Injection in Delphi - Nick Hodges [2017]
- Dependency Injection with Unity - Dominic Betts, et al. [2013]
- Mastering Ninject for Dependency Injection - Daniel Baharestani [2013]
- Dependency Injection in .NET - Mark Seemann [2011]
- Dependency Injection With Examples in Java, Ruby, and C# - Dhanji R. Prasanna [2009]
Books are presented in opposite order of publication