项目作者: benhurott

项目描述 :
A light, pure javascript, dependency free injection "framework" for javascript projects.
高级语言: JavaScript
项目地址: git://github.com/benhurott/pureinject.git
创建时间: 2018-11-21T04:20:48Z
项目社区:https://github.com/benhurott/pureinject

开源协议:MIT License

下载


pureinject

A light, pure javascript, dependency free injection “framework” for javascript projects.

travis-master

logo

Setup

Just add to your dependencies using NPM or Yarn:

  1. npm install pureinject

or

  1. yarn add pureinject

How to use

  1. const { createInjector } = require('pureinject');
  2. class MyHttpService {
  3. // ...
  4. }
  5. class MyService {
  6. constructor(injector) {
  7. this._httpService = injector.resolve('MyHttpService');
  8. }
  9. }
  10. const injector = createInjector();
  11. injector.register('MyHttpService', injector => {
  12. return new MyHttpService();
  13. });
  14. injector.register('MyService', injector => {
  15. return MyService(injector);
  16. });

With Typescript

  1. import { createInjector, PureInjector } from 'pureinject'
  2. class MyHttpService {
  3. // ...
  4. }
  5. class MyService {
  6. private _httpService: MyHttpService
  7. constructor(injector: PureInjector) {
  8. this._httpService = injector.resolve<MyHttpService>('MyHttpService');
  9. }
  10. }
  11. const injector: PureInjector = createInjector()
  12. injector.register('MyHttpService', (injector: PureInjector) => {
  13. return new MyHttpService();
  14. })
  15. injector.register('MyService', (injector: PureInjector) => {
  16. return MyService(injector);
  17. });

How it works

It’s simple: each time you call injector.resolve, it will run the the registered function and will retrieve the new instance of the service.

You can return what you want inside a registered module.

If you want to resolve a string value, you can!

  1. const { createInjector } = require('pureinject');
  2. class HttpService {
  3. constructor(injector) {
  4. this._apiUrl = injector.resolve('API_URL');
  5. }
  6. }
  7. const injector = createInjector();
  8. injector.register('API_URL', injector => {
  9. return 'https://api.site.com';
  10. });
  11. injector.register('HttpService', injector => {
  12. return new HttpService(injector);
  13. });

About

Thanks to

Icons made by Freepik from www.flaticon.com is licensed by CC 3.0 BY