0
0
Expressframework~10 mins

Dependency injection in Express - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Dependency injection in Express
Create dependencies
Inject dependencies into middleware or routes
Express app uses injected dependencies
Handle requests using injected services
Send response
This flow shows how dependencies are created, injected into Express routes or middleware, and then used to handle requests.
Execution Sample
Express
const express = require('express');
const app = express();

const logger = { log: msg => console.log('LOG:', msg) };

app.get('/', (req, res) => {
  logger.log('Home route accessed');
  res.send('Hello');
});
This code creates a logger dependency and injects it into the route handler to log messages when the route is accessed.
Execution Table
StepActionDependency StateEffect
1Create logger objectlogger = { log: function }Logger ready to use
2Define route '/' with injected loggerlogger available in routeRoute can call logger.log
3Request to '/' receivedlogger unchangedRoute handler runs
4Call logger.log('Home route accessed')logger logs messageConsole shows: LOG: Home route accessed
5Send response 'Hello'logger unchangedClient receives 'Hello'
6Request handled fullyNo changesWaiting for next request
💡 Request completes after response is sent, dependency remains ready for next use
Variable Tracker
VariableStartAfter Step 1After Step 3After Step 5Final
loggerundefined{ log: function }{ log: function }{ log: function }{ log: function }
requndefinedundefined{ request object }{ request object }undefined
resundefinedundefined{ response object }{ response object }undefined
Key Moments - 3 Insights
Why does the logger object stay the same throughout the request?
Because the logger is created once and injected as a shared dependency; it is not recreated per request (see execution_table steps 1 and 3).
How does the route handler access the logger dependency?
The logger is available in the route's scope because it was defined outside and used inside the route callback (execution_table step 2).
What happens if we modify the logger inside a request?
Modifying the logger would affect all future requests since it's shared; typically, dependencies are kept stateless or carefully managed (not shown in this example).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the state of 'logger' after step 3?
AUndefined
BAn object with a log function
CA string message
DNull
💡 Hint
Check the 'Dependency State' column at step 3 in the execution_table
At which step does the console output 'LOG: Home route accessed' appear?
AStep 5
BStep 2
CStep 4
DStep 6
💡 Hint
Look at the 'Effect' column describing console output in the execution_table
If the logger was recreated inside the route handler, how would the variable tracker change?
ALogger would have different instances after each request
BLogger would be null after step 3
CLogger would be undefined at start and after step 1
DLogger would not appear in variable tracker
💡 Hint
Consider how variable values change when a new object is created per request, referencing variable_tracker
Concept Snapshot
Dependency injection in Express:
- Create dependencies (e.g., services, loggers) outside routes
- Inject them by referencing in route handlers or middleware
- Allows easy reuse and testing
- Keeps code clean and modular
- Dependencies stay consistent across requests unless recreated
Full Transcript
Dependency injection in Express means creating reusable objects like loggers or services outside route handlers and then using them inside routes. This way, the same dependency is shared and used whenever a request comes in. The flow starts by creating dependencies, then injecting them into routes, handling requests using these dependencies, and finally sending responses. The example shows a logger object created once and used inside a route to log messages when the route is accessed. The logger remains the same across requests, ensuring consistent behavior. This approach helps keep code organized and easy to test.