https://github.com/zhang740/power-di
A lightweight Dependency Injection library.
https://github.com/zhang740/power-di
Last synced: 2 months ago
JSON representation
A lightweight Dependency Injection library.
- Host: GitHub
- URL: https://github.com/zhang740/power-di
- Owner: zhang740
- License: mit
- Created: 2017-03-16T09:26:50.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2025-01-21T05:35:35.000Z (6 months ago)
- Last Synced: 2025-04-27T05:19:12.452Z (3 months ago)
- Language: TypeScript
- Size: 276 KB
- Stars: 178
- Watchers: 1
- Forks: 9
- Open Issues: 2
-
Metadata Files:
- Readme: README.md
- Changelog: History.md
- License: LICENSE
Awesome Lists containing this project
- awesome-nodejs - power-di - A lightweight Dependency Injection library.  (Repository / Inversion of control / Dependency Injection (Ioc/DI))
README
# Power DI
[](https://travis-ci.org/zhang740/power-di)
[](https://coveralls.io/github/zhang740/power-di)
[](https://www.npmjs.com/package/power-di)
[](https://github.com/zhang740/power-di/blob/master/LICENSE)A lightweight Dependency Injection library. Using es6 and other features, remove unnecessary concepts, easy and convenient to use.
## Install
```shell
npm i power-di --save
```## Example
### a simple example
```ts
import { IocContext } from 'power-di';class AService { }
// default instance, you can also new IocContext to get a instance.
const context = IocContext.DefaultInstance;
context.register(AService);
const aService = context.get(AService); // a instance of AService
```### inject with key
```ts
class AService { }const context = IocContext.DefaultInstance;
context.register(AService, 'XService'); // key need a string or class, e.g super class or whatever class.
context.get('XService');
```### use with decorators
```ts
const context = new IocContext();@injectable()
class NRService { }@injectable()
class LITestService {
@inject()
public testService: NRService;
}const test = context.get(LITestService);
```### collect impl or extends of some interface/base class
```ts
class A { }@classInfo()
class B extends A { }@classInfo()
class C extends A { }@injectable()
class LITestService {
@imports({ type: A })
public testService: A[];
}const test = context.get(LITestService); // test.testService as A[];
```### use in react
```tsx
const context = new IocContext;
class NRService { }
context.register(NRService);class TestComponent extends Component<{}, {}> {
@inject()
service: NRService;componentDidMount() {
t.true(this.service instanceof NRService);
}render(): any {
return null;
}
}create(
);
```## Class Loader
Power DI introduced the concept of class loader. We can customize the find rule of ioc.#### [See the test case for details.](https://github.com/zhang740/power-di/tree/master/test)