Skip to content

Instantly share code, notes, and snippets.

@greenido
Created November 3, 2024 00:13
Show Gist options
  • Save greenido/938beb608ff7780751036c43b1b29cc2 to your computer and use it in GitHub Desktop.
Save greenido/938beb608ff7780751036c43b1b29cc2 to your computer and use it in GitHub Desktop.
Property, Method, and Container DI Examples in TypeScript
// 1. Basic interfaces and implementations
interface ILogger {
log(message: string): void;
}
interface IEmailSender {
send(to: string, message: string): void;
}
class ConsoleLogger implements ILogger {
log(message: string): void {
console.log(`[LOG]: ${message}`);
}
}
class EmailSender implements IEmailSender {
send(to: string, message: string): void {
console.log(`Sending email to ${to}: ${message}`);
}
}
// 2. PROPERTY INJECTION
class NotificationManager {
// Properties that can be injected after creation
public logger?: ILogger;
public emailSender?: IEmailSender;
notify(user: string, message: string): void {
// Optional chaining used since dependencies might not be injected
this.logger?.log(`Sending notification to ${user}`);
this.emailSender?.send(user, message);
}
}
// Usage of Property Injection
const notificationManager = new NotificationManager();
notificationManager.logger = new ConsoleLogger();
notificationManager.emailSender = new EmailSender();
notificationManager.notify("[email protected]", "Hello!");
// 3. METHOD INJECTION
class ReportGenerator {
// Dependencies are passed directly to the method that needs them
generateReport(data: string, logger: ILogger): void {
logger.log("Starting report generation");
logger.log(`Report content: ${data}`);
logger.log("Report generation complete");
}
}
// Usage of Method Injection
const reportGenerator = new ReportGenerator();
const logger = new ConsoleLogger();
reportGenerator.generateReport("Sales data for Q1", logger);
// 4. DI CONTAINER
class Container {
private dependencies: Map<string, any> = new Map();
// Register a dependency
register<T>(key: string, implementation: T): void {
this.dependencies.set(key, implementation);
}
// Get a dependency
resolve<T>(key: string): T {
const dependency = this.dependencies.get(key);
if (!dependency) {
throw new Error(`Dependency ${key} not found!`);
}
return dependency as T;
}
}
// Usage of DI Container
// 1. Create container
const container = new Container();
// 2. Register dependencies
container.register('logger', new ConsoleLogger());
container.register('emailSender', new EmailSender());
// 3. Create a service that uses the container
class UserService {
private logger: ILogger;
private emailSender: IEmailSender;
constructor(container: Container) {
this.logger = container.resolve('logger');
this.emailSender = container.resolve('emailSender');
}
createUser(email: string): void {
this.logger.log(`Creating user: ${email}`);
this.emailSender.send(email, "Welcome to our service!");
}
}
// 4. Use the service
const userService = new UserService(container);
userService.createUser("[email protected]");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment