TypeDI: TypeScript Dependency Injection

0.10.0 · active · verified Sun Apr 19

TypeDI is a dependency injection framework specifically designed for TypeScript and JavaScript applications. It enables the creation of loosely coupled, well-structured, and easily testable applications in both Node.js and browser environments. The current stable version is 0.10.0, with releases occurring periodically to introduce new features, improvements, and bug fixes, as indicated by the recent 0.9.x to 0.10.0 progression. Key differentiators include support for both property and constructor-based injection, management of singleton and transient services, and the ability to work with multiple DI containers within a single application. It heavily leverages TypeScript decorators and the `reflect-metadata` polyfill to achieve its injection capabilities, making proper configuration of `tsconfig.json` crucial for its operation.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates basic setup with `reflect-metadata` and TypeDI's `@Service()` decorator for both constructor and property injection, including usage of environment variables.

import 'reflect-metadata';
import { Container, Service } from 'typedi';

// A service that will be injected
@Service()
class MailerService {
  private readonly apiKey: string;

  constructor() {
    this.apiKey = process.env.MAILER_API_KEY ?? 'default-api-key';
  }

  sendMail(to: string, subject: string, body: string): void {
    console.log(`Sending email to ${to} with subject '${subject}' via API Key: ${this.apiKey}`);
    console.log(`Body: ${body}`);
  }
}

// A service that depends on MailerService
@Service()
class UserService {
  constructor(private mailer: MailerService) {}

  registerUser(email: string, username: string): void {
    console.log(`Registering user: ${username} (${email})`);
    this.mailer.sendMail(email, 'Welcome!', `Hello ${username}, welcome to our service!`);
  }
}

// Get an instance of UserService from the container, which will automatically inject MailerService
const userService = Container.get(UserService);

userService.registerUser('john.doe@example.com', 'JohnDoe');

// You can also get other services directly
const mailerService = Container.get(MailerService);
mailerService.sendMail('admin@example.com', 'System Alert', 'Server running fine!');

view raw JSON →