mench / dependency-injection-es6

MIT License
16 stars 1 forks source link

Error: undefined must be class not a undefined #2

Closed devmondo closed 7 years ago

devmondo commented 7 years ago

hi, the below is causing the error

@singleton
@inject(B)
export class A {
    constructor(b) {
        this.b = b;
    }
}

@inject(C)
export class B {
    constructor(c) {
        this.c =c;
        console.log(this.c);
    }
}

@inject(A)
export class C {
    constructor(a) {
        this.a =a;
        console.log(this.a);
    }
}
mench commented 7 years ago

Hi @devmondo I think it can't be solved in javascript (es6) because of runtime B class still is undefined for A and C for B. javascript runtime interpreter can't recognize it.

devmondo commented 7 years ago

oh ! thank you very much :) well the above is just fast code, the real code is that i put each one of them in file and import them.

so A and B work, the problem is C, i think it is cyclic issue or i may be wrong

mench commented 7 years ago

Yes you are right it is cyclic references problem and also this problem exist on typescript. There are custom solutions for them one of them is https://github.com/casser/typescript-cyclic-references-problem

devmondo commented 7 years ago

aha! i see, so this has to be implemented in your lib to make it work?

mench commented 7 years ago

No. Just you can use this logic on your code // cached.js export function Cached(target,key,desc){ var initializer = desc.get; desc.get = function(){ return Object.defineProperty(this,key,{ value:initializer() })[key]; }; return desc; } // one.js import {Cached} from "./cached"; import {Two} from "./two"; export class One { @Cached static get two():Two{ return new Two() } } // two.js import {Cached} from "./cached"; import {One} from "./one"; export class Two { @Cached static get one():One{ return new One(); } } //main.js import {One} from "./one" import {Two} from "./two" console.info(One.two) console.info(Two.one)

mench commented 7 years ago

Otherwise I think cyclic reference problem should solve in babel compiler.

devmondo commented 7 years ago

@mench thank you man :) hope it is fixed somehow with babel

mench commented 7 years ago

Thank you too :)