Dependency injection is a programming technique.
Instead of hard-coding the list of functions you call, you get the functions as input parameters. The caller is responsible for making sure you have the functions you need.
We call these functions dependencies.
// without dependency injection
//
// `logger` and `dbConn` in this case are probably
// global variables
function queryDatabase(sql: string): unknown {
logger.logInfo("querying database: " + sql);
return dbConn.query(sql);
}
// with dependency injection
//
// `logger` and `dbConn` are given to you
// `Logger` and `DatabaseConnection` are
// *interfaces* and not class names
function queryDatabase(
logger: Logger,
dbConn: DatabaseConnection,
sql: string
): unknown {
logger.logInfo("querying database: " + sql);
return dbConn.query(sql);
}
Dependency injection is often mistaken for the dependency inversion principle from the SOLID principles. It belongs to the Inversion of Control (IoC) programming principle instead.