Let's say I have a Simple Factory (SimpleProductFactory
) that uses a condition parameter to determine how to create Product
s like this:
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;
}
}
This factory is used by some client that handles runtime data containing the condition like this:
public class SomeClient
{
// ...
public void HandleRuntimeData(RuntimeData runtimeData)
{
Product product = SimpleProductFactory.MakeProduct(runtimeData.Condition);
// use product...
}
// ...
}
public class RuntimeData
{
public Condition Condition { get; set; }
// ...
}
How can I achieve the same construction behavior using Unity 2.0?
The important part is that the condition (Condition
) determines how to create and setup the Product
, and that the condition is only known at runtime and differs for each MakeProduct(...)
call. (The "Other product setup code" deals with some delegate stuff, but could also be handling other initializations, and needs to be part of the construction.)
How should the container registration of Product
(or an IProduct inteface) be done?
Should I use an InjectionFactory
construction? How do I do that?
// How do I do this?
container.RegisterType<Product>(???)
What do I need to do to be able to supply the condition in the client code?
Naïve client code (from a previous edit) to highlight the last question, that explains the wordings of a couple of the answers:
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...
}
// ...
}
(I have read through a lot of similar questions here at Stackoverflow but haven't been able to fit them, and their answers, to my needs.)