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

The Mechanism

class WebServer {
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) => {
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
// Using the methods granted from the injection of router features
// The original listen methods all instances of WebServer have

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