hardLow-Level Design

Explain 'dependency injection' and how it can be used in Node.js.

442 views
01

Understand the problem

This question assesses knowledge of a fundamental software design pattern for modularity and testability.

design patternsdependency injectiontestingmodularity
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

Manual constructor injection
class UserService {
  constructor({ repo, mailer, logger }) {  // deps injected
    this.repo = repo; this.mailer = mailer; this.logger = logger;
  }
  async register(data) {
    const u = await this.repo.save(data);
    await this.mailer.send(u.email, 'welcome');
    return u;
  }
}
// composition root wires real deps; tests pass fakes:
const svc = new UserService({ repo: new PgUserRepo(), mailer, logger });
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.