2016-10-06 5 views
1

私はシンプルなインジェクターで、次の組み合わせを登録しようとしている:例えば、具体的なタイプのIMyInterfaceの(1以上)の実装のSimple Injectorを使用して条件付きでコレクションを登録する方法は?

  1. コレクション、フォールバックとしてオープンジェネリックタイプIMyInterface<T>ためImplementation1<MyClass>IMyInterface<MyClass>
  2. ダミーコレクション(空のリスト)についてImplementation2<MyClass>(条件付き?)

私はIEnumerable<IMyInterface<T>>のすべての要求者がで取得することを確実にしたい。この方法少なくとも空のリストまたは実際の実装のリストIEnumerable<IMyInterface<MyClass>>のリクエスタは、要素Implementation1<MyClass>Implementation2<MyClass>で列挙可能なインスタンス(例:List<IMyInterface<MyClass>>)を取得し、リクエスタIEnumerable<IMyInterface<AnotherClass>>Enumerable.Empty<IMyInterface<AnotherClass>>となるはずです。

クラスのリストは、登録コードに固定されていません。私は、アセンブリからすべての実装を収集するブートストラップを実装しました。

私はRegisterCollectionRegisterConditionalのいくつかの組み合わせを使用してみましたが、誰もがすべての要件を満たしていません。 RegisterCollectionConditionalの(存在しない)回避策がありますか?

+0

関連:https://github.com/simpleinjector/SimpleInjector/issues/283 – Steven

+0

実装がコレクションに表示される条件を説明(または表示)できますか? – Steven

+0

その情報がなければ、あなたに良い答えを与えることは不可能です。 – Steven

答えて

1

あなたがしたいことは、Simple Injectorでは特別なものは必要ありません。シンプルインジェクターを自動であなたのための任意のタイプを選択します。次のタイプを仮定:

class Implementation1 : IMyInterface<MyClass> { } 
class Implementation2 : IMyInterface<MyClass> { } 
class Implementation3 : IMyInterface<FooBarClass>, IMyInterface<MyClass> { } 

次のように登録になります。

container.RegisterCollection(typeof(IMyInterface<>), new[] { 
    typeof(Implementation1), 
    typeof(Implementation2), 
    typeof(Implementation3), 
}); 

これは、次になります:

// returns: Implementation1, Implementation2, Implementation3. 
container.GetAllInstances<IMyInterface<MyClass>>(); 

// returns: Implementation3. 
container.GetAllInstances<IMyInterface<FooBarClass>>(); 


// returns: empty list. 
container.GetAllInstances<IMyInterface<AnotherClass>>(); 

代わりに、手動ですべてのタイプを登録し、あなたもできます一括登録を使用します。

container.RegisterCollection(typeof(IMyInterface<>), 
    typeof(Implementation1).Assembly); 

これはすべての実装を登録します(すべてが同じアセンブリ内にあると仮定します)。場合

しかし、あなたは、次の種類があります。

class Implementation1<T> : IMyInterface<T> { } 
class Implementation2<T> : IMyInterface<T> { } 
class Implementation3<T> : IMyInterface<T> { } 

あなたは、以下の登録を行うことができます。

:私たちは前に見てきたように、この登録は、同じ結果につながる

container.RegisterCollection(typeof(IMyInterface<>), new[] { 
    typeof(Implementation1<MyClass>), 
    typeof(Implementation2<MyClass>), 
    typeof(Implementation3<MyClass>), 
    typeof(Implementation3<FooBarClass>), 
}); 

// returns: Implementation1<MyClass>, Implementation2<MyClass>, Implementation3<MyClass>. 
container.GetAllInstances<IMyInterface<MyClass>>(); 

// returns: Implementation3<FooBarClass>. 
container.GetAllInstances<IMyInterface<FooBarClass>>(); 

// returns: empty list. 
container.GetAllInstances<IMyInterface<AnotherClass>>(); 

詳細については、collections sectionおよびを参照してください。を参照してください。

関連する問題