Dependency Injection for C++

Dependency injection is a technique that allows classes to be more flexible because it removes dependency from the class so class can be used with objects it didn't create. This idea is well-known in Java environment, but for C++ it can be also used - to some degree.

Dependency injection in a simplest form can be explained with the following code:

class MyClass1 {
private:
  OdbcDatabaseConnection *connection;
public:
  MyClass1() {
    connection = new OdbcDatabaseConnection("user=tester;password=12345");
  }
  ~MyClass1() {
    delete connection;
  }
};

In this example MyClass1 cannot be used with other connection classes (for example Oracle or DB2) because it creates connection by itself. To use dependency injection here it is enough to specify connection as abstract-class constructor parameter:

class MyClass1 {
private:
  IDatabaseConnection *connection;
public:
  MyClass1(IDatabaseConnection *aConnection) {
    this->connection = aConnection;
  }
};

In this code above MyClass1 can be used with any connection that is derived from IDatabaseConnection interface (abstract class) which is useful for example during unit testing when real connection cannot be provided.

Tutorials

Solutions

IoC (Inversion of Control) containers

Share

follow