2016-11-23 7 views
1

TypeScriptでInversifyJSを使用しています。InversifyJSのパラメータを持つファクトリー

のは、私が注入され、非注射コンストラクタのパラメータの混合持つクラスがあるとしましょう:

@injectable() 
export class MyClass { 
    constructor(
     foo: Foo, // This thing isn't injectable 
     @inject(Bar) bar: Bar // This thing is 
    ){ 
     ... 
    } 
} 

は、私はいくつかの他のクラスに、このクラスのファクトリを注入し、その後でそれを呼び出すしたいと思いますが最初のパラメータの値。

@injectable() 
export class SomeOtherClass { 
    constructor(
     @inject("Factory<MyClass>") myClassFactory: (foo: Foo) => MyClass 
    ){ 
     const someFoo = new Foo(); 
     const myClass = myClassFactory(someFoo); 
    } 
} 

私の質問:私はこの工場を注入できるようになりますInversifyにおけるいくつかのオートマジックはありますか?

bind<interfaces.Factory<MyClass>>("Factory<MyClass>").toFactory(context => 
    (foo: Foo) => 
     new MyClass(foo, context.kernel.get<Bar>(Bar)) 
); 

しかし、それは私が明示的にnew() -ing MyClassMyClassのすべての新しい注射用の依存関係があまりにもここで追加する必要がありますよ意味:

私がこれまでに作ってみた最高のはこれです。

良い方法がありますか?おそらくNinject Factory Extensionsのようなパラメータ名に基づくものでしょうか?

答えて

0

私はInversifyJSの著者です。ファクトリー内でnewを使用する際に問題があるとは思わないが、工場の仕事はの新しいインスタンスを作成することです。

工場内でcontainer.get<T>を複数回呼び出すことは、not a good thingです。

私はフェーズへへMyClassの初期化を壊す提案することができます:

工場によってインスタンスクラス:

@injectable() 
export class MyClass { 

    public c: C; // This thing isn't injectable 
    public d: D; // This thing isn't injectable 

    // PHASE 1: instantiation 
    constructor(
     @inject(A) a: A // This thing is 
     @inject(B) b: B // This thing is 
    ){ 
     ... 
    } 

    // PHASE 2: initialization 
    public init(c: C, d: D) { 
     this.c = c; 
     this.d = d; 
    } 

} 

工場使用するクラス:

@injectable() 
export class SomeOtherClass { 
    constructor(
     @inject("Factory<MyClass>") myClassFactory: (c: C, d: D) => MyClass 
    ){ 
     // you only use "new" with entities that are not injected by inversify 
     const c = new C(); 
     const d = new D(); 
     const myClass = myClassFactory(c, d); 
    } 
} 

そして、工場:

bind<interfaces.Factory<MyClass>>("Factory<MyClass>").toFactory(context => 
    (c: C, d, D) => { 

     // PHASE 1: instantiation 
     let myClass = context.kernel.get<MyClass>("MyClass"); // a and b are injected 

     // PHASE 2: initialization 
     myClass.init(c, d); // c and d are initialized 

     return myClass; 

    } 
); 

もっと良い方法を知っていると思うのであれば、GitHubの問題に関するあなたのアイデアを共有してください。

+1

ありがとうございます。間違いなく、クラスのすべての依存関係を 'get()'しなければならないことが改善されています。つまり、私はGitHubで別のアプローチを提案するかもしれません。 –

関連する問題