-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (54 loc) · 2.13 KB
/
index.js
File metadata and controls
61 lines (54 loc) · 2.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class DIContainer {
constructor() {
this.services = new Map();
this.instances = new Map();
}
register(name, factory, dependencies = []) {
this.services.set(name, { factory, dependencies });
}
resolve(name) {
if (this.instances.has(name)) {
return this.instances.get(name);
}
const service = this.services.get(name);
if (!service) throw new Error(`Service ${name} not found`);
const dependencies = service.dependencies.map(dep => this.resolve(dep));
const instance = service.factory(...dependencies);
this.instances.set(name, instance);
return instance;
}
}
class ConsoleLogger {
log(message) {
console.log(`[LOG] ${new Date().toLocaleTimeString()} - ${message}`);
}
}
class EmailService {
constructor(logger) { this.logger = logger; }
sendEmail(to, subject, body) {
this.logger.log(`Preparing email to: ${to}`);
console.log(`Sending email to: ${to}`);
console.log(`Subject: ${subject}`);
console.log(`Body: ${body}`);
this.logger.log(`Email sent to: ${to}`);
}
}
class NotificationService {
constructor(emailService, logger) {
this.emailService = emailService;
this.logger = logger;
}
sendWelcomeNotification(userEmail, userName) {
this.logger.log(`Processing notification for: ${userName}`);
this.emailService.sendEmail(userEmail, "Welcome!", `Hello ${userName}, welcome to our platform!`);
this.logger.log("Notification completed");
}
}
console.log("Email Notification DI Example Starting...\n");
const container = new DIContainer();
container.register('logger', () => new ConsoleLogger());
container.register('emailService', (logger) => new EmailService(logger), ['logger']);
container.register('notificationService', (emailService, logger) => new NotificationService(emailService, logger), ['emailService', 'logger']);
const notificationService = container.resolve('notificationService');
notificationService.sendWelcomeNotification("john@example.com", "John");
console.log("\nEmail Notification DI worked successfully!");