Guides
Introduction

Getting started

💡

It is highly recommended to learn a thing or two about dependency injection before moving on.

Installation

Inside your project, run the following:

yarn add @wendellhu/redi

or use other package managers such as npm:

npm install @wendellhu/redi

After installation, you should enable experimentalDecorators in the tsconfig.json file:

{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

Basic usage

Let's get started with an example:

class AuthService {
  public static getCurrentUserInfo(): UserInfo {
    // your implementation here...
  }
}
 
class FileListService {
  constructor() {}
 
  public getUserFiles(): Promise<Files> {
    const currentUser = AuthService.getCurrentUserInfo()
    // ...
  }
}

Obviously FileListService depends on AuthService. Let's see how we can make this piece of code dependency injection flavour.

Step One. Declare dependency relationship.

import { Inject } from '@wendellhu/redi'
 
class AuthService {
  public getCurrentUserInfo(): UserInfo {
    // your implementation here...
  }
}
 
class FileListService {
  constructor(@Inject(AuthService) private readonly authService: AuthService) {}
 
  public getUserFiles(): Promise<Files> {
    const currentUser = this.authService.getCurrentUserInfo()
    // ...
  }
}

Use the decorator Inject to declare on the constructor of FileListService that AuthService is one of its dependencies.

Step Two: Provide dependencies.

import { Injector } from '@wendellhu/redi'
 
const injector = new Injector([[FileListService], [AuthService]])

All your have to do is pass them into the constructor of Injector.

Step Three. Wire up.

const fileListService = injector.get(FileListService)

Then you get an instance of FileListService, and its dependency AuthService is also constructed and cached in the `Injector.

const authService = injector.get(FileListService)

Read the next chapter to learn basic concepts in dependency injection.