What are the three types of dependency injection? The three styles most often named are constructor injection, setter injection and interface injection. They differ in how the dependency reaches the class. Some sources group the styles differently, for example as constructor, method and property injection, so the names can vary between books and articles.
Constructor injection
The dependency is passed to the constructor and stored. The object is complete from the moment it exists, because it cannot be created without its dependency.
#include <memory>
#include <string>
#include <utility>
class Logger {
public:
virtual ~Logger() = default;
virtual void log(const std::string& message) = 0;
};
class Report {
public:
explicit Report(std::unique_ptr<Logger> logger)
: logger_(std::move(logger)) {}
void generate() {
logger_->log("Report generated");
}
private:
std::unique_ptr<Logger> logger_;
};
This is the default choice for most C++ classes. Since the constructor requires a logger, you never end up with a Report that is missing one. The trade-off is a longer parameter list when a class needs many dependencies. A long list can be a hint that the class has too many responsibilities.
Setter injection
The dependency is passed to a setter method after the object exists. This suits optional dependencies, or ones you may want to replace later.
#include <string>
class Logger {
public:
virtual ~Logger() = default;
virtual void log(const std::string& message) = 0;
};
class Report {
public:
void set_logger(Logger* logger) {
logger_ = logger;
}
void generate() {
if (logger_ != nullptr) {
logger_->log("Report generated");
}
}
private:
Logger* logger_ = nullptr; // not owned
};
The risk is that the object can exist without its dependency. The class has to check for nullptr before using it, or its users must remember to call the setter first. Report does not own the logger here, so the caller must keep the logger alive for as long as the report uses it.
Interface injection
Interface injection is less common in C++. The class implements an interface with a method that accepts the dependency, and an injector calls that method to supply it. Because the injector works through the interface, it can handle many classes in the same way.
#include <string>
class Logger {
public:
virtual ~Logger() = default;
virtual void log(const std::string& message) = 0;
};
// The interface an injector uses to hand over a logger
class LoggerReceiver {
public:
virtual ~LoggerReceiver() = default;
virtual void receive_logger(Logger* logger) = 0;
};
class Report : public LoggerReceiver {
public:
void receive_logger(Logger* logger) override {
logger_ = logger;
}
void generate() {
if (logger_ != nullptr) {
logger_->log("Report generated");
}
}
private:
Logger* logger_ = nullptr; // not owned
};
Each dependency needs its own interface, so interface injection usually adds more code than the other two styles. It can help when a framework needs one uniform way to hand dependencies to many classes.
Which style to choose
- Use constructor injection by default. It keeps dependencies required and the object valid from the start.
- Use setter injection for optional dependencies, or when a dependency may need to be replaced after creation.
- Use interface injection when a shared mechanism must supply dependencies to many classes in the same way.
A fourth style: method injection
Some write-ups add a fourth style, sometimes called method injection. The dependency is passed as an argument to the one method that needs it, and the class does not store it. This fits when only one operation needs the dependency.