Skip to content

Dependency injection library for JavaScript and TypeScript in 5.1K. It is an extraction of the Angular's dependency injection which means that it's feature complete, fast, reliable and well tested.

Notifications You must be signed in to change notification settings

galtalmor/injection-js

 
 

Repository files navigation

Build Status

Dependency Injection

Dependency injection library for JavaScript and TypeScript in 5.2K. It is an extraction of the Angular's dependency injection which means that it's feature complete, fast, reliable and well tested.

Up-to-date with Angular 4.1.

How to use?

$ npm i injection-js --save

Note that for ES5 Class syntax and TypeScript you need a polyfill for the Reflect API. You can use, for instance, reflect-metadata, or core-js (core-js/es7/reflect).

TypeScript

import 'reflect-metadata';
import { ReflectiveInjector, Injectable, Injector } from 'injection-js';

class Http {}

@Injectable()
class Service {
  constructor(private http: Http) {}
}

@Injectable()
class Service2 {
  constructor(private injector: Injector) {}
  
  getService(): void {
    console.log(this.injector.get(Service) instanceof Service);
  }
  
  createChildInjector(): void {
    const childInjector = ReflectiveInjector.resolveAndCreate([
      Service
    ], this.injector);
  }
}

const injector = ReflectiveInjector.resolveAndCreate([
  Service,
  Http
]);

console.log(injector.get(Service) instanceof Service);

Note: you will need to enable the TypeScript flags experimentalDecorators and emitDecoratorMetadata to make this work.

ES6

const { Inject, ReflectiveInjector } = require('injection-js');

class Http {}

class Service {
  static get parameters() {
    return [new Inject(Http)];
  }

  constructor(http) {
    this.http = http;
  }
}

const injector = ReflectiveInjector.resolveAndCreate([Http, Service]);

console.log(injector.get(Service) instanceof Service);

ES5

require('reflect-metadata');
var di = require('injection-js');

var Http = di.Class({
  constructor: function () {}
});

var Service = di.Class({
  constructor: [Http, function (http) {
    this.http = http;
  }]
});

var injector = di.ReflectiveInjector.resolveAndCreate([Http, Service]);

console.log(injector.get(Service) instanceof Service);

For full documentation click here, here and here.

License

MIT

About

Dependency injection library for JavaScript and TypeScript in 5.1K. It is an extraction of the Angular's dependency injection which means that it's feature complete, fast, reliable and well tested.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • TypeScript 99.9%
  • JavaScript 0.1%