{"id":12780,"library":"typedi","title":"TypeDI: TypeScript Dependency Injection","description":"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.","status":"active","version":"0.10.0","language":"javascript","source_language":"en","source_url":"https://github.com/pleerock/typedi","tags":["javascript","typescript"],"install":[{"cmd":"npm install typedi","lang":"bash","label":"npm"},{"cmd":"yarn add typedi","lang":"bash","label":"yarn"},{"cmd":"pnpm add typedi","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for emitting decorator metadata, which TypeDI relies on heavily for dependency resolution.","package":"reflect-metadata","optional":false}],"imports":[{"note":"TypeDI is primarily designed for ESM consumption, especially with TypeScript decorators. CommonJS `require` is generally discouraged due to potential metadata issues and awkward syntax.","wrong":"const Container = require('typedi').Container;","symbol":"Container","correct":"import { Container } from 'typedi';"},{"note":"`Service` is a named export, not a default export. Ensure correct destructuring.","wrong":"import Service from 'typedi';","symbol":"Service","correct":"import { Service } from 'typedi';"},{"note":"This import must be the very first line of your application's entry point to ensure the `Reflect` API is available globally before any decorators are processed.","wrong":"require('reflect-metadata');","symbol":"'reflect-metadata'","correct":"import 'reflect-metadata';"}],"quickstart":{"code":"import 'reflect-metadata';\nimport { Container, Service } from 'typedi';\n\n// A service that will be injected\n@Service()\nclass MailerService {\n  private readonly apiKey: string;\n\n  constructor() {\n    this.apiKey = process.env.MAILER_API_KEY ?? 'default-api-key';\n  }\n\n  sendMail(to: string, subject: string, body: string): void {\n    console.log(`Sending email to ${to} with subject '${subject}' via API Key: ${this.apiKey}`);\n    console.log(`Body: ${body}`);\n  }\n}\n\n// A service that depends on MailerService\n@Service()\nclass UserService {\n  constructor(private mailer: MailerService) {}\n\n  registerUser(email: string, username: string): void {\n    console.log(`Registering user: ${username} (${email})`);\n    this.mailer.sendMail(email, 'Welcome!', `Hello ${username}, welcome to our service!`);\n  }\n}\n\n// Get an instance of UserService from the container, which will automatically inject MailerService\nconst userService = Container.get(UserService);\n\nuserService.registerUser('john.doe@example.com', 'JohnDoe');\n\n// You can also get other services directly\nconst mailerService = Container.get(MailerService);\nmailerService.sendMail('admin@example.com', 'System Alert', 'Server running fine!');","lang":"typescript","description":"Demonstrates basic setup with `reflect-metadata` and TypeDI's `@Service()` decorator for both constructor and property injection, including usage of environment variables."},"warnings":[{"fix":"Upgrade to the latest stable version and review the official documentation for API changes, especially around `@Service` and `Container` methods.","message":"TypeDI versions prior to 0.6.0 had slightly different decorator application and API for registering services. While 0.10.0 is stable, always consult release notes for major version updates from older versions.","severity":"breaking","affected_versions":"<0.6.0"},{"fix":"Add `import 'reflect-metadata';` to the absolute top of your main application file (e.g., `src/main.ts` or `app.ts`).","message":"The `reflect-metadata` package *must* be imported as the very first line of your application's entry file. Failing to do so will result in runtime errors related to missing metadata when decorators are processed.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Ensure the specified `compilerOptions` are present in your `tsconfig.json` file. Without them, decorators will not function as expected for DI.","message":"TypeDI relies on TypeScript's experimental decorators and metadata emission. Your `tsconfig.json` must include `\"emitDecoratorMetadata\": true` and `\"experimentalDecorators\": true` under `compilerOptions`.","severity":"gotcha","affected_versions":">=0.1.0"},{"fix":"Refactor your services to break circular dependencies, perhaps by introducing an interface, an event emitter, or restructuring responsibilities. Lazy injection patterns might also help in specific scenarios.","message":"Circular dependencies can occur when Service A depends on Service B, and Service B also depends on Service A. TypeDI can sometimes resolve simple circular dependencies with constructor injection if not deeply nested, but complex cases can lead to runtime errors or `undefined` injections.","severity":"gotcha","affected_versions":">=0.1.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Ensure `import 'reflect-metadata';` is the absolute first line in your main application file before any other imports.","cause":"`reflect-metadata` was not imported, or not imported as the very first line of your application.","error":"TypeError: Reflect.metadata is not a function"},{"fix":"Verify that `MyService` has `@Service()` applied. Check `tsconfig.json` for `emitDecoratorMetadata` and `experimentalDecorators`. Inspect dependency graph for circular references.","cause":"The class intended for injection either lacks the `@Service()` decorator or the container cannot resolve its dependencies due to a misconfiguration or circular dependency.","error":"Error: Service 'MyService' was not found in the container. Make sure you have decorated it with @Service() and registered it."},{"fix":"Add `\"reflect-metadata\"` to the `types` array in your `tsconfig.json`'s `compilerOptions`, or ensure `\"lib\": [\"esnext\", \"dom\"]` (or similar) is present which often includes `esnext.reflect`.","cause":"TypeScript compiler is unaware of the `Reflect` global object, likely because `reflect-metadata` is installed but not included in `tsconfig.json`'s `types` or `lib`.","error":"TS2304: Cannot find name 'Reflect'."}],"ecosystem":"npm"}