Sobes.tech
Middle

Tell me about Inversion of Control and Dependency Injection.

sobes.tech AI

Answer from AI

Inversion of Control (IoC) is a principle where the control of creating and binding objects is delegated to an external container or framework, rather than being implemented directly within components. This reduces coupling and increases code flexibility.

Dependency Injection (DI) is a specific implementation of IoC, where an object's dependencies are provided to it from outside (via constructor, setters, or interfaces), rather than being created internally.

Example in Java:

public class Service {
    private final Repository repo;

    // Dependency is injected via constructor
    public Service(Repository repo) {
        this.repo = repo;
    }

    public void doWork() {
        repo.save();
    }
}

Here, Service does not create Repository itself but receives it from outside. This simplifies testing and replacing implementations.

IoC and DI are widely used in the Spring Framework, where the container manages the lifecycle and dependency injection.