How to use the IoC Container?

Jul 23, 2015 at 1:57 PM
Hello, I have troubles to use the IoC Container. Can anyone take a look at my sample code whats wrong here?

ts sample

thanks
Coordinator
Jul 24, 2015 at 3:29 PM
Edited Jul 24, 2015 at 3:29 PM
Hi,
this should work:

module CordovaTestApp.Common.IoC {
class Utils {
    static getClassTypeName(instanceType: { new (): Object }) : string {
        var funcNameRegex = /function (.{1,})\(/;
        var results = (funcNameRegex).exec(instanceType.prototype["constructor"].toString());
        return (results && results.length > 1) ? results[1] : "";
    }
}

export class Container {
    //Dictionary containing object instances
    private static instances: { [type: string]: Object; } = {};

    //Resolve a specific Type by returning the instance from the Dictionary
    static resolve<T>(instanceType: { new (): T }): Object {
        var name = Utils.getClassTypeName(instanceType);
        return Container.instances[name];
    }

    //Register a specific instance in the Dictionary
    static register<T>(instanceType: { new (): T }, instance: Object) {
        var name = Utils.getClassTypeName(instanceType);
        Container.instances[name] = instance;
    }
}
}

module CordovaTestApp {
"use strict";

export class Test1  {       
}

export class Test2  {
}

export class Test3  {
}

export class Test4  {
}
}

module CordovaTestApp {
"use strict";
function registerIoC() {

    Common.IoC.Container.register(Test1, new Test1());
    Common.IoC.Container.register(Test2, new Test2());
            Common.IoC.Container.register(Test3, new Test3());
            Common.IoC.Container.register(Test4, new Test4());
}

registerIoC();

var t1 = Common.IoC.Container.resolve(Test3)
alert(t1.constructor.name);
}
Jul 24, 2015 at 4:01 PM
Hello davidezordan,

thanks a lot for your fix. Works great now and this IoC is super simple :)

Thanks!
Coordinator
Jul 24, 2015 at 6:00 PM
You're welcome, glad it helped.