TypeDI

Simple yet powerful dependency injection tool for JavaScript and TypeScript...

README

TypeDI


Build Status
codecov
npm version
Dependency Status

TypeDI is a dependency injection tool for TypeScript and JavaScript. With it you can build well-structured and easily testable applications in Node or in the browser.

Main features includes:

- property based injection
- constructor based injection
- singleton and transient services
- support for multiple DI containers

Installation


Note: This installation guide is for usage with TypeScript, if you wish to use

TypeDI without Typescript please read the documentation about how get started.


To start using TypeDI install the required packages via NPM:

  1. ```bash
  2. npm install typedi reflect-metadata
  3. ```

Import the reflect-metadata package at the first line of your application:

  1. ```ts
  2. import 'reflect-metadata';

  3. // Your other imports and initialization code
  4. // comes here after you imported the reflect-metadata package!
  5. ```

As a 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. ```json
  2. "emitDecoratorMetadata": true,
  3. "experimentalDecorators": true,
  4. ```

Now you are ready to use TypeDI with Typescript!

Basic Usage


  1. ```ts
  2. import { Container, Service } from 'typedi';

  3. @Service()
  4. class ExampleInjectedService {
  5.   printMessage() {
  6.     console.log('I am alive!');
  7.   }
  8. }

  9. @Service()
  10. class ExampleService {
  11.   constructor(
  12.     // because we annotated ExampleInjectedService with the @Service()
  13.     // decorator TypeDI will automatically inject an instance of
  14.     // ExampleInjectedService here when the ExampleService class is requested
  15.     // from TypeDI.
  16.     private injectedService: ExampleInjectedService
  17.   ) {}
  18. }

  19. const serviceInstance = Container.get(ExampleService);
  20. // we request an instance of ExampleService from TypeDI

  21. serviceInstance.injectedService.printMessage();
  22. // logs "I am alive!" to the console
  23. ```

Documentation


The detailed usage guide and API documentation for the project can be found:

- at [docs.typestack.community/typedi][docs-stable]
- in the ./docs folder of the repository

[docs-stable]: https://docs.typestack.community/typedi/
[docs-development]: https://docs.typestack.community/typedi/v/develop/

Contributing


Please read our contributing guidelines to get started.