Don't confuse DIP, IoC, and DI together. They are all different but related.
DIP (or Dependency Inversion Principle)
is one of the principles of SOLID. SOLID stands for:
- Single responsibility - a class should only have one responsibility
- Open / closed principle - a class should be open for extension but closed for modification
- Liskov substitution principle - a class should be replaceable without altering the functionality of the whole
- Interface segregation principle - better to have more specific interfaces than a general purpose one
- Dependency inversion principle - a higher-level class should never depend on a lower-level class, instead higher-level class should define an abstraction that lower-level class should depend on
IoC (or Inversion of Control) is a paradigm that adheres to the dependency inversion principle by inverting the control to avoid dependencies. Most inversions can be generalized into these three types of control:
- Control over interface - consumer class should have control over the interface and provider classes should depend on that interface
- Control over flow - a “don’t call us, we’ll call you” paradigm
- Control over creation - where creating objects is done outside of the class they are being used in
DI (or Dependency Injection) is one way of inverting control over creation (other ways being the factory method and the service locator). It moves the creation and binding of a dependency outside of the class that depends on it. Common types of dependency injection:
- Constructor injection
- Setter injection
- Interface injection
Additional Resources: