Dependency Injection
Dependency Injection
A design technique where the parts a program needs are handed in from outside instead of being built inside the program.
In Simple Terms
Dependency injection is a way of building a program so that it receives the parts it needs from the outside instead of creating them itself. Because those parts can be swapped out later, it's handy when you want to change how a program behaves without rewriting its main code. For example, it's used to hand over one part in production and a different one in testing, or when an underlying framework quietly connects the parts for you behind the scenes.
Behind the Name
In "dependency injection," a "dependency" is the relationship that exists when one part needs another part in order to work. "Injection" captures the image of pouring the needed part in from the outside and handing it over. It's often abbreviated to DI, taking the initials of the two words.
Take a Closer Look!
Dependency injection is a design approach where a program gets the other parts it needs handed to it from the outside, instead of creating them directly inside itself. Rather than tying parts together permanently from the start, you set things up so they can be combined from the outside at the moment the program runs.
Think of an appliance: instead of building the battery permanently into the device, you make it so you can pop in whatever battery you like.
If you write a part directly into your program, then when you want to change that part later, you'll need to rewrite the main code extensively too. If the part is handed in from outside, you can swap in a different one to suit the situation without touching the main code at all.
For example, in production you might pass in a part that connects to the real database, and only during testing pass in a stand-in part instead.
Designing things so parts are handed in also keeps each part independent, which makes it easier to check or replace individual pieces even as the project grows. In real development, it's not always a person passing parts in by hand every time. Often a framework, the foundation that a piece of software is built on, automatically prepares and hands over the parts for you.
It's widely used in software made by combining multiple parts, such as the behind-the-scenes processing of web services and app development.