I am trying to figure out when to use the DIC/IoC registry for configuring my software and when to use factories, along with the reasoning behind either approach.
I am using StructureMap as my DI container (DIC), which is easy to configure using registries. In the DIC practically all registered objects are static in the sense, that I do not need to change/exchange any implementation/instance at runtime, once the DIC is configured and they are configured in the DIC as singletons. However, since my software (SW) will run on different devices I do need to select a device-specific registry depending on the device that my SW runs on in order to configure the hardware accordingly.
Since the construction of some my objects requires reading in configuration files, I am using factories to return these instances to the DIC, in order to separate the reading of the configuration from the creation of the object. I registered the factory getters in the DIC for the corresponding plugin types.
Now say I have a plugin type
IMotor with concrete types
Motor2, which should be handled by a factory. There are now two ways I can decide how to configure my device:
- I pass information about the device that the SW is running on to a
MotorFactoryand it returns the correct motor, either
Motor2. In this case the logic for deciding is inside the Factory.
- I configure the DIC according to the device it is running on and create two factories
Motor2Factory, where one creates
Motor1and the other
Motor2. In this case I would have differing registry entries for
IMotorin the device-specific registries which use either
Now my question is: Which one of these two methods are preferable and why? To me, it seems the first case is not straight forward and a convoluted, since I am spreading out the logic that decides what type to instantiate throughout the code-base. Whereas in the second case I am effectively multiplying the number of factories in my code, since I will need a factory for (almost) each concrete type. It becomes even more confusing to me, when abstract factories are added to the mix.
So again: When should I use one method or the other? And more importantly: What are good indicators for deciding which way to go?