Dependency Injection
Subject: Computer and Technology noun /dɪˈpɛn.dən.si ɪnˈdʒɛk.ʃən/ 1 definition
- software-engineering
- design-patterns
- software-architecture
- object-oriented-programming
-
Definition (noun)
Entry #87 · UpdatedDependency Injection (DI) is a software design pattern and form of inversion of control in which a component receives the external services or objects it relies on from an outside caller or framework rather than instantiating or locating them internally. By binding consumers to abstract interfaces instead of concrete classes, DI separates business logic from dependency construction, lifecycle management, and configuration. Unlike the service locator pattern—where components actively pull dependencies from a central registry—DI pushes collaborators inward, making requirements explicit, improving modularity, and simplifying automated testing with mock or stub implementations.
Common Forms
Constructor Injection: Passes required dependencies as arguments to a class constructor at instantiation time, ensuring the object is initialized in a valid state with immutable references.
Setter Injection: Supplies optional or reconfigurable dependencies through public setter methods or writable properties after an object has already been constructed.
Method Injection: Delivers a dependency directly as a parameter to an individual method invocation, scoping that collaborator strictly to a single operation.
Example
An
OrderServiceclass accepts aPaymentGatewayinterface in its constructor rather than instantiating a concreteStripeClientinside its checkout method. In production, the application's DI container injects a liveStripeGatewayconfigured with API credentials, whereas the automated test suite injects an in-memory fake gateway to verify billing logic without making real network calls.