Dependency Injection
Dependency Injection Jgql1
π¨βπΌ Now let's see the power of composition! We can swap different logger
implementations without changing
EmailService. This is dependency injectionβa
key benefit of composition.Logger and EmailService from the previous step are already provided.
EmailService.sendEmail(to, subject) produces
Sending email to ${to}: ${subject} through whatever logger you inject (and
also on the console).π¨ Open
and:
- Create and export a
MockLoggerthatextends Logger:- Override
log(message)to store each message in order (do not print) - Expose
getLogs(): Array<string>that returns the stored messages
- Override
- Create and export a
SilentLoggerthatextends Logger:- Override
log(message)to do nothing (no print, no storage, no throw)
- Override
- Demonstrate that the existing
EmailServiceworks with both loggers - Export:
export { Logger, EmailService, MockLogger, SilentLogger }
Fixtures and success criteria
const mockLogger = new MockLogger()
mockLogger.log('Test message 1')
mockLogger.log('Test message 2')
const emailService = new EmailService(mockLogger)
emailService.sendEmail('test@example.com', 'Test Subject')
const silentLogger = new SilentLogger()
const silentEmail = new EmailService(silentLogger)
silentEmail.sendEmail('user@example.com', 'Welcome')
mockLogger.getLogs()starts as['Test message 1', 'Test message 2']beforesendEmail- After
sendEmail('test@example.com', 'Test Subject'),getLogs()includes'Sending email to test@example.com: Test Subject' silentLogger instanceof Loggeristrue- Using
SilentLoggerwithEmailServicedoes not throw - The same
EmailServiceAPI works unchanged with either logger
π° This is the power of dependency injection:
EmailService doesn't care which
logger it getsβit just uses whatever logger is provided. This makes testing easy
and allows you to swap implementations at runtime.π Dependency Injection


