Was the angular2 dependency injection container designed for standalone use, and is it possible to use it for typescript/javascript server-side applications ?

I opened an issue on Oct. 16 (https://github.com/angular/di.js/issues/108) on the di project which was I guess supposed to make it into v2. Apparently this was not possible. What's up with the new angular2 di ? Can I use it in a standalone fashion with js / es6 / ts projects?

share|improve this question

This question has an open bounty worth +300 reputation from estus ending in 5 hours.

The question is widely applicable to a large audience. A detailed canonical answer is required to address all the concerns.

2  
In the issue you linked, It is not easy to use it as standalone atm and there is no documentation for such setup. There is a plan to extract DI library from the **angular2** repo in the future, but this is not the case today. Also, nice hat! – caffinatedmonkey Dec 25 '15 at 2:41
    
It's speaking about the angular2 di. – caffinatedmonkey Dec 25 '15 at 2:43
    
Oh I see you're right. But things might have changed now! Angular2 wasn't out at the time. – Ludo Dec 25 '15 at 2:48
1  
"It’s an isolated component of the framework that can be used as standalone system, without Angular 2 " blog.thoughtram.io/angular/2015/05/18/… – Ludo Dec 25 '15 at 2:54
1  
That's the thing. I'm reading all sort of stuff all over the place. I'd like to know once for all if I can use angular2 Di elsewhere. – Ludo Dec 26 '15 at 17:41

I doubt it, it doesn't look like it has been extracted into a component. It's a bit sad that major frameworks like Angular still have this monolithic approach, I would rather like to see Component oriented frameworks like Symfony, but JavaScript isn't quite there yet.

In the meantime you have InversifyJS that doesn't look bad.

share|improve this answer
1  
It inconvenient that DI is mixed with non-relevant stuff, but core A2 features don't depend on the platform, so it should be possible at least, just not sure how good the things are (NPM package is relatively small and contains pre-built ES5 and ES6). Btw, we already got Aurelia DI as a componentized alternative, not documented for Node usage too. – estus Aug 8 at 22:40

At the moment the Angular 2.0 DI code doesn't seem to be ready to be consumed by other libraries.

I would like to suggest an alternative. I have developed an IoC container called InversifyJS with advanced dependency injection features like contextual bindings. It works in both node and browsers and some parts of its API are based on the Angular 2 DI API.

You need to follow 3 basic steps to use it:

1. Add annotations

The annotation API is based on Angular 2.0:

import { injectable, inject } from "inversify";

@injectable()
class Katana implements IKatana {
    public hit() {
        return "cut!";
    }
}

@injectable()
class Shuriken implements IShuriken {
    public throw() {
        return "hit!";
    }
}

@injectable()
class Ninja implements INinja {

    private _katana: IKatana;
    private _shuriken: IShuriken;

    public constructor(
        @inject("IKatana") katana: IKatana,
        @inject("IShuriken") shuriken: IShuriken
    ) {
        this._katana = katana;
        this._shuriken = shuriken;
    }

    public fight() { return this._katana.hit(); };
    public sneak() { return this._shuriken.throw(); };

}

2. Declare bindings

The binding API is based on Ninject:

import { Kernel } from "inversify";

import { Ninja } from "./entities/ninja";
import { Katana } from "./entities/katana";
import { Shuriken} from "./entities/shuriken";

var kernel = new Kernel();
kernel.bind<INinja>("INinja").to(Ninja);
kernel.bind<IKatana>("IKatana").to(Katana);
kernel.bind<IShuriken>("IShuriken").to(Shuriken);

export default kernel;

3. Resolve dependencies

The resolution API is based on Ninject:

import kernel = from "./inversify.config";

var ninja = kernel.get<INinja>("INinja");

expect(ninja.fight()).eql("cut!"); // true
expect(ninja.sneak()).eql("hit!"); // true

The latest release (2.0.0) supports many use cases:

  • Universal JavaScript (Works in Node.js and Browsers)
  • Kernel modules
  • Kernel middleware
  • Use classes, string literals or Symbols as dependency identifiers
  • Injection of constant values
  • Injection of class constructors
  • Injection of factories
  • Auto factory
  • Injection of providers (async factory)
  • Activation handlers (used to inject proxies)
  • Multi injections
  • Tagged bindings
  • Custom tag decorators
  • Named bindings
  • Contextual bindings
  • Friendly exceptions (e.g. Circular dependencies)

You can learn more about it at https://github.com/inversify/InversifyJS

share|improve this answer

Checkout ubiquits sources - he did somehow integrated angular 2's DI on the backend.

If you want simple but powerfull and painless dependency injection tool for typescript and node.js typedi. It works great with angular frontends too. Also checkout other repositories of this author, there are lot of components that will help you to build node applications using TypeScript.

share|improve this answer

As of Angular 2 RC.5, DI is a part of @angular/core package and also depends on reflect-metadata package, even if TypeScript/ES.next decorators aren't used.

Here is a short ES6 Node-friendly example that excites my anticipation for a dinner:

require('reflect-metadata');

const { Inject } = require('@angular/core');
const { Injector, ReflectiveInjector, OpaqueToken, Provider } = require('@angular/core');

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([
    new Provider('bread', { useValue: 'bread' }),
    new Provider(bread, { useValue: 'bread' }),
    new Provider(cutlet, { useValue: 'cutlet' }),
    Sandwich,
]);

const sandwich = rootInjector.get(Sandwich);

Hope that the other answers can show how Angular 2 hierarchical injectors can be used in non-Angular application.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.