Was the angular2 dependency injection container designed for standalone use, and is it possible to use it for typescript/javascript server-side applications ?
I open
As of Angular 2 RC.5, DI is a part of @angular/core
package. For non-Angular uses, it was recently extracted into injection-js
package by Minko Gechev, a member of Angular team.
Here is a short ES6, Node-friendly example:
// may not be needed for injection-js and recent @angular/core versions
// if ES5-flavoured `Class` helper isn't used
require('reflect-metadata');
const { Inject, Injector, ReflectiveInjector, OpaqueToken } = require('@angular/core');
// or ... = require('injection-js');
const bread = new OpaqueToken;
const cutlet = new OpaqueToken;
class Sandwich {
constructor(bread, cutlet, injector) {
const anotherBread = injector.get('bread');
injector === rootInjector;
bread === 'bread';
anotherBread === 'bread';
cutlet === 'cutlet';
}
}
Sandwich.parameters = [
new Inject(bread),
new Inject(cutlet),
new Inject(Injector)
];
const rootInjector = ReflectiveInjector.resolveAndCreate([
{ provide: 'bread', useValue: 'bread' },
{ provide: bread, useValue: 'bread' },
{ provide: cutlet, useValue: 'cutlet' },
Sandwich
]);
const sandwich = rootInjector.get(Sandwich);