条件パラメーターを使用してs を次のように作成する方法を決定するSimple Factory ( SimpleProductFactory
)があるとします。Product
public static class SimpleProductFactory
{
public static Product MakeProduct(Condition condition)
{
Product product;
switch(condition)
{
case Condition.caseA:
product = new ProductA();
// Other product setup code
break;
case Condition.caseA2:
product = new ProductA();
// Yet other product setup code
break;
case Condition.caseB:
product = new ProductB();
// Other product setup code
break;
}
return product;
}
}
このファクトリは、次のような条件を含むランタイム データを処理するクライアントによって使用されます。
public class SomeClient
{
// ...
public void HandleRuntimeData(RuntimeData runtimeData)
{
Product product = SimpleProductFactory.MakeProduct(runtimeData.Condition);
// use product...
}
// ...
}
public class RuntimeData
{
public Condition Condition { get; set; }
// ...
}
Unity 2.0 を使用して同じ構築動作を実現するにはどうすればよいですか?
重要な部分は、条件 ( Condition
) によって の作成方法とセットアップ方法が決定されることと、条件が実行時にのみ認識され、呼び出しProduct
ごとに異なることです。MakeProduct(...)
(「その他の製品セットアップ コード」は、一部のデリゲートを処理しますが、他の初期化も処理する可能性があり、構築の一部である必要があります。)
Product
(または IProduct インターフェイス)のコンテナー登録はどのように行う必要がありますか? コンストラクション
を使用する必要がありますか?InjectionFactory
それ、どうやったら出来るの?
// How do I do this?
container.RegisterType<Product>(???)
クライアント コードで条件を指定できるようにするには、どうすればよいですか?
いくつかの回答の文言を説明する最後の質問を強調する単純なクライアント コード (以前の編集から):
public class SomeClient
{
// ...
public void HandleRuntimeData(RuntimeData runtimeData)
{
// I would like to do something like this,
// where the runtimeData.Condition determines the product setup.
// (Note that using the container like this isn't DI...)
Product product = container.Resolve<Product>(runtimeData.Condition);
// use product...
}
// ...
}
(ここStackoverflowで同様の質問をたくさん読みましたが、それらとその回答を私のニーズに合わせることができませんでした。)