What is the Inversion of Control (IoC) principle, and how does dependency injection relate to it as one specific technique?
Short answer
IoC is the broader principle that a component should NOT control the creation/lifecycle of its own dependencies — control is 'inverted' to an external source (a framework, container, or calling code).
Advertisement
AModel answer
IoC is the broader principle that a component should NOT control the creation/lifecycle of its own dependencies — control is 'inverted' to an external source (a framework, container, or calling code). Dependency injection is ONE common technique for achieving IoC (others include the Service Locator pattern or event-driven/callback-based inversion), specifically by passing dependencies in rather than the component reaching out to fetch them.
// IoC in action: the FRAMEWORK controls when/how OrderService is created and injected,
// not OrderService's own code or its direct caller
public class OrdersController {
public OrdersController(IOrderService orderService) { /* framework provides this */ }
}Real-world example
Understanding DI as a specific implementation of the broader IoC principle, distinguishing it from other IoC techniques like the Service Locator pattern.
Likely follow-ups
- Why is the Service Locator pattern generally considered an inferior alternative to constructor-based DI?
Related topics