Why do developers use dependency injection in Express applications?
Think about how you can swap parts of your app during tests.
Dependency injection helps by letting you replace real parts with fake ones during testing, making tests simpler and more reliable.
Consider this middleware that uses a service injected via req.services. What will it send as a response?
app.use((req, res, next) => {
const message = req.services.greetingService.getMessage();
res.send(message);
});Assume req.services.greetingService is properly injected and has a getMessage method returning a string.
If the service is injected correctly, calling getMessage() returns the greeting string, which is sent as the response.
Choose the code snippet that properly adds a userService to each request using middleware.
Remember that req is the request object passed to handlers.
Only option A correctly attaches the service to req, making it accessible in later middleware and routes.
Given this middleware, why does accessing req.services.dataService cause a TypeError?
app.use((req, res, next) => {
req.services.dataService = new DataService();
next();
});
app.get('/', (req, res) => {
res.send(req.services.dataService.getData());
});Check if req.services exists before assigning properties.
The middleware tries to assign dataService to req.services, but req.services is undefined, causing a TypeError.
Consider this code where a singleton service counts requests. What will the response be after three requests?
class CounterService { constructor() { this.count = 0; } increment() { this.count++; return this.count; } } const counterService = new CounterService(); app.use((req, res, next) => { req.counter = counterService; next(); }); app.get('/', (req, res) => { const currentCount = req.counter.increment(); res.send(`Request number: ${currentCount}`); });
Think about how the singleton service keeps state across requests.
The singleton counterService keeps its count property across requests, so after three requests, the count is 3.