What is Inversion of Control (IoC)?
sobes.tech AI
Answer from AI
Inversion of Control (IoC) is a design principle where the flow of control of a program is inverted. Instead of an object creating or looking up its dependencies itself, this responsibility is delegated to an external entity, usually an IoC container. The container injects the necessary dependencies into the object.
Main aspects of IoC:
- Responsibility Delegation: The object does not manage its dependencies but only defines them.
- Separation of Creation and Usage: The code using the object is separated from the code creating its dependencies.
- Simplified Testing: Dependencies can be easily replaced with mock objects.
There are several techniques for implementing IoC:
-
Dependency Lookup: The object actively searches for its dependencies in the container.
// Pseudo-code example class MyService { private Dependency dependency; public MyService() { // The object actively looks up the dependency this.dependency = IoCContainer.lookup("myDependency"); } // ... } -
Dependency Injection: The container passively injects dependencies into the object. This is a more common approach.
There are three main types of dependency injection:
-
Constructor Injection: Dependencies are provided through the constructor.
// Example class MyService { private final Dependency dependency; // Dependency is injected via constructor public MyService(Dependency dependency) { this.dependency = dependency; } // ... } -
Setter Injection: Dependencies are provided through setter methods.
// Example class MyService { private Dependency dependency; // Dependency is injected via setter public void setDependency(Dependency dependency) { this.dependency = dependency; } // ... } -
Field Injection: Dependencies are injected directly into fields using annotations (often used by frameworks).
// Example using Spring class MyService { @Autowired // Annotation instructs the framework to inject the dependency private Dependency dependency; // ... }
-
IoC is a key principle in frameworks like Spring and Guice, facilitating the creation of loosely coupled and modular code.