Understanding Dependency Injection

The Basic Idea

An Example

// Web Server Classclass WebServer {  //Constructor takes one argument, an object with several properties including port
constructor(config = {port: 3000}) {
this.port = config.port;
}
//function to theoretically kickoff server listener
listen() {
console.log(`listening on port ${this.port}`);
}
}
// Create New Instance of Web Server
const app = new WebServer({port: 4000});
// Server Starts Listening
app.listen()

The Mechanism

class WebServer {
constructor(
config = {
port: 3000,
deps: [],
}
) {
this.port = config.port;
// loops over each dependency and passes the instance to the function so it can add any methods or properties for that features set
config.deps.forEach((dep) => {
dep(this);
});
}
listen() {
console.log(`listening on port ${this.port}`);
}
}
// Mock injection of routing function
const routeInject = (server) => {
server.get = () => console.log('this is a get route')
server.put = () => console.log('this is a put route')
server.post = () => console.log('this is a post route')
server.delete = () => console.log('this is a delete route')
}
// Mock injection of postgres database functions
const pgInject = (server) => {
server.pgConnect = () => console.log('connected to db')
server.query = () => console.log('query database')
}
const app = new WebServer({
port: 4000,
// I add any injection functions in the deps array, they get to run in the constructor adding the methods to the instance of the web server
deps: [routeInject, pgInject]
});
// Using the methods granted from the injection of postgres features
app.pgConnect()
app.query()
// Using the methods granted from the injection of router features
app.get()
app.post()
// The original listen methods all instances of WebServer have
app.listen();

Alex Merced is a Full Stack Developer, learn more about his work at AlexMercedCoder.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store