Dependency injection is a way to provide parts (dependencies) that a piece of code needs, instead of creating them inside the code. In Express, it means passing services or objects to routes or middleware instead of hardcoding them.
Click to reveal answer
beginner
Why use dependency injection in Express apps?
It helps keep code clean and easy to test. You can swap parts without changing the main code, making your app more flexible and easier to maintain.
Click to reveal answer
intermediate
How can you inject a database connection into an Express route?
You can create the database connection outside the route and pass it as a parameter or attach it to the request object using middleware, so the route can use it without creating it again.
Click to reveal answer
intermediate
Example: What does this code do?
const app = express();
const service = new Service();
app.use((req, res, next) => {
req.service = service;
next();
});
This middleware adds a service instance to every request as req.service. Routes can then use req.service to access the service without creating it themselves.
Click to reveal answer
intermediate
What is a common pattern to inject dependencies in Express without global variables?
Use middleware to attach dependencies to the request object or use factory functions that create routes with dependencies passed as arguments.
Click to reveal answer
What is the main goal of dependency injection in Express?
ATo pass dependencies to routes instead of creating them inside
BTo make routes slower
CTo avoid using middleware
DTo hardcode all dependencies inside routes
✗ Incorrect
Dependency injection means passing dependencies to routes or middleware instead of creating them inside, making code cleaner and easier to test.
How can you provide a database connection to all routes in Express?
AUse global variables only
BCreate a new connection inside each route
CAttach the connection to req object using middleware
DIgnore the connection and fetch data directly
✗ Incorrect
Attaching the database connection to the req object via middleware allows all routes to access it without recreating it.
Which of these is NOT a benefit of dependency injection?
AMore flexible code
BHarder to maintain code
CEasier testing
DBetter separation of concerns
✗ Incorrect
Dependency injection makes code easier to maintain, not harder.
What does this middleware do?
app.use((req, res, next) => { req.logger = logger; next(); });
ACreates a new logger for each request
BStops the request from continuing
CRemoves the logger from requests
DAttaches a logger instance to each request
✗ Incorrect
This middleware adds a logger instance to the req object so routes can use it.
Which pattern helps avoid global variables when injecting dependencies?
AUsing factory functions to create routes with dependencies
BCreating dependencies inside routes
CIgnoring dependencies
DUsing global variables everywhere
✗ Incorrect
Factory functions allow passing dependencies as arguments, avoiding global variables.
Explain how dependency injection improves testing in Express applications.
Think about how you can swap parts when testing.
You got /3 concepts.
Describe two ways to inject dependencies into Express routes.
One way involves middleware, the other involves functions that return routes.
You got /2 concepts.
Practice
(1/5)
1. What is the main purpose of dependency injection in an Express app?
easy
A. To provide parts of the app with the resources they need without hardcoding them
B. To make the app run faster by caching data
C. To automatically generate routes based on file names
D. To handle errors globally in the app
Solution
Step 1: Understand dependency injection concept
Dependency injection means giving parts of your app what they need instead of making them find it themselves.
Step 2: Identify the purpose in Express
In Express, this helps keep code organized and flexible by passing dependencies explicitly.
Final Answer:
To provide parts of the app with the resources they need without hardcoding them -> Option A
Quick Check:
Dependency injection = Provide needed resources [OK]
Hint: Think: "Give what is needed, don't make it find" [OK]
Common Mistakes:
Confusing dependency injection with caching
Thinking it auto-generates routes
Mixing it with error handling
2. Which of the following is the correct way to inject a service into an Express router?
easy
A. const router = express.Router(); router.use(service);
B. const router = express.Router(service);
C. function createRouter(service) { const router = express.Router(); router.service = service; return router; }
D. const router = express.Router(); router.service = service();
Solution
Step 1: Check how to pass dependencies in Express
Express.Router() does not accept parameters directly, so passing service as argument is invalid.
Step 2: Use a factory function to inject service
Creating a function that takes service and returns a router with service attached is the correct pattern.
Final Answer:
function createRouter(service) { const router = express.Router(); router.service = service; return router; } -> Option C
Quick Check:
Inject by factory function = function createRouter(service) { const router = express.Router(); router.service = service; return router; } [OK]
Hint: Use a function to pass dependencies, not Router constructor [OK]
Common Mistakes:
Passing service directly to express.Router()
Calling service as a middleware incorrectly
Assigning service without a factory function
3. Consider this code snippet:
function createService() {
return { getName: () => 'MyService' };
}
function createRouter(service) {
const router = require('express').Router();
router.get('/name', (req, res) => {
res.send(service.getName());
});
return router;
}
const service = createService();
const router = createRouter(service);
// What happens when a GET request is made to '/name'?
medium
A. The server will crash due to missing middleware
B. The response will be undefined
C. There will be a runtime error because service is not defined
D. The response will be 'MyService'
Solution
Step 1: Analyze service creation
The createService function returns an object with getName method returning 'MyService'.
Step 2: Analyze router handler
The router uses the injected service and calls getName to send the response on '/name' route.
Final Answer:
The response will be 'MyService' -> Option D
Quick Check:
Injected service method returns 'MyService' [OK]
Hint: Injected service methods run as expected in route handlers [OK]