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:
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.
Using redi with CDN
You can also use redi via CDN if you don’t want to use npm or yarn.
Include the following <script>
tag in your HTML file:
<script src="https://unpkg.com/@wendellhu/redi/dist/umd/index.js"></script>
Redi will be mounted on the global variable @wendellhu/redi
, and you can access it via window["@wendellhu/redi"]
.
If you want to use redi with React, you can include the following <script>
tag:
<script src="https://unpkg.com/@wendellhu/redi/dist/umd/react-bindings/index.js"></script>
Redi’s React API will be mounted on the global variable @wendellhu/redi/react-bindings
, and you can access it via window["@wendellhu/redi/react-bindings"]
.
If you are using React 19, you should import the React bindings using JavaScript modules:
<script type="module">
import { Inject, Injector } from "https://unpkg.com/@wendellhu/redi/dist/esm/index.js";
import { connectDependencies } from "https://unpkg.com/@wendellhu/redi/dist/esm/react-bindings/index.js";
</script>