Sobes.tech
Intern

What is the difference between Dependency Injection and Dependency Inversion?

sobes.tech AI

Answer from AI

Dependency Injection (DI) and Dependency Inversion (DIP) are related but different concepts in software design.

  • Dependency Inversion Principle (DIP) is one of the five SOLID principles. It states that:

    1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
    2. Abstractions should not depend on details. Details should depend on abstractions.

    This principle aims to reduce coupling and increase flexibility of architecture.

  • Dependency Injection (DI) is a pattern (method) for implementing inversion of dependencies. DI means that the dependencies of an object are passed to it from outside (for example, via constructor, setter, or interface), rather than being created inside the object.

Example of DI in C++:

class ILogger {
public:
    virtual void Log(const std::string& message) = 0;
};

class ConsoleLogger : public ILogger {
public:
    void Log(const std::string& message) override {
        std::cout << message << std::endl;
    }
};

class Application {
    ILogger& logger;
public:
    Application(ILogger& logger) : logger(logger) {}
    void Run() {
        logger.Log("App started");
    }
};

int main() {
    ConsoleLogger logger;
    Application app(logger); // dependency injection
    app.Run();
}

In summary: DIP is a design principle, and DI is a way to implement it.

What is the difference between Dependency Injection… - sobes.tech