TypeDI
Search…
Getting Started
TypeDI is a dependency injection library for TypeScript and JavaScript.

Installation

Note: This installation guide is for usage with TypeScript, if you wish to use TypeDI without Typescript please read the getting started guide for JavaScript.
To start using TypeDI install the required packages via NPM:
1
npm install typedi reflect-metadata
Copied!
Import the reflect-metadata package at the first line of your application:
1
import 'reflect-metadata';
2
3
// Your other imports and initialization code
4
// comes here after you imported the reflect-metadata package!
Copied!
As the last step, you need to enable emitting decorator metadata in your Typescript config. Add these two lines to your tsconfig.json file under the compilerOptions key:
1
"emitDecoratorMetadata": true,
2
"experimentalDecorators": true,
Copied!
Now you are ready to use TypeDI with Typescript!

Basic Usage

The most basic usage is to request an instance of a class definition. TypeDI will check if an instance of the class has been created before and return the cached version or it will create a new instance, cache, and return it.
1
import { Container, Service } from 'typedi';
2
3
@Service()
4
class ExampleInjectedService {
5
printMessage() {
6
console.log('I am alive!');
7
}
8
}
9
10
@Service()
11
class ExampleService {
12
constructor(
13
// because we annotated ExampleInjectedService with the @Service()
14
// decorator TypeDI will automatically inject an instance of
15
// ExampleInjectedService here when the ExampleService class is requested
16
// from TypeDI.
17
public injectedService: ExampleInjectedService
18
) {}
19
}
20
21
const serviceInstance = Container.get(ExampleService);
22
// we request an instance of ExampleService from TypeDI
23
24
serviceInstance.injectedService.printMessage();
25
// logs "I am alive!" to the console
Copied!
Last modified 9d ago
Copy link