I’m attempting to inject a dependency that varies by the state passed in. For example, if the state is Wisconsin, I want to inject one class, but if it’s Illinois, I want another. It’s not 1-for-1, but 7 states for one and 3 for another.
Is there a way in Spring.net to have a list of values to check against in the config xml?
This is the subject of chapter 6.1 “Mapping runtime values to abstractions” of the book Dependency Injection in .NET. The solution suggested there is to use an
Abstract Factory. Your abstract factory might look like:And inject this factory on your consumer that knows which state to process. To get an
IStateAlgorithmhis consumer then calls yOptionally, you could create a simple factory that maps state names to instances managed by your spring container if you want full configuration control.
Simple example
I imagine you have several classes that implement a certain
IStateAlgorithm:And that there is a certain
Consumerthat needs to pick an algorithm based on a runtime value. The consumer can be injected with a factory, from which it can retrieve the algorithm it needs:A simple factory implementation would simply switch on the state value, use an if, or look in internal list:
Spring.Net Configurable example
If you would like to be able to configure your
IStateAlgorithmin your spring configuration, you can introduce aLookupStateAlgorithmFactory. This example assumes that yourIStateAlgorithms are stateless and can be shared among consumers:The xml config could be: