0.1.1 • Published 7 years ago

inject-ts v0.1.1

Weekly downloads
2
License
MIT
Repository
github
Last release
7 years ago

inject.ts

TypeScript Dependency Injection Library

Node.js

Add it to your package.json or install it with NPM:

$ npm install inject-ts

For using in scripts dependency

///<reference path="node_modules/inject-ts/inject.d.ts"/>

Quick Start

TypeScript Class Inner

Create a class and inject it into the Context by adding the Class Decorator @Inject. A Singleton of this class will now be available in the Context. This class can now be injected into another class through constructor injection.

import {Injectable} from "inject";

@Injectable
class Inner {

    constructor() {
    }

}

TypeScript Class Outer -- Constructor Injection

Create a class that is added to the Context. Use the Parameter Decorator @Provide(<T>) passing in the parameter class type of the parameters to the constructor. When this class is retrieved from Context, the parameters will have been injected.

import {Inject, Injectable} from "inject";
import {Inner} from "./inner";

@Injectable
class Outer {

    private _inner:Inner;

    constructor(@Inject(Inner) inner:Inner) {
        this._inner = inner;
    }
}

TypeScript Class Outer -- Property Injection

Create a class that is added to the Context. Use the Property Decorator @Provide(<T>) passing in the property class type. When this class is retrieved from the Context, the properties will have been injected.

import {Inject, Injectable} from "inject";
import {Inner} from "./inner";

@Injectable
class Outer {

    @Inject(Inner)
    private _inner:Inner;

}

TypeScript Class Main

In the main class, get the outer class from the Context by typing the return type and passing in the class type that is being requested.

import {Context} from "inject";
import {Outer} from "./Outer";

var outer:Outer = Context.getContext().get<Outer>(Outer);

Add an external object to the Context

External objects can be added to the Context. First, create the object with all of it's requirements. Second, call set(name:string, obj:any) on the `Context' passing the name the object should be found by and the object.

import * as http from "http";

Context.getContext().set("<string name>", http);

Retrieve an external object from the Context

External objects can be retrieved from the context by passing in a name to the Decorator @Inject.

import * as http from "http";

class Temp {

    @Inject("<string name>")
    private _http:http;
    private _http2:http;

    constructor(@Inject("<string name>")http:http) {
        this._http2 = http;
    }
}