I have done something similar before and took an approach very similar to the one Fabiano has suggested.
Sample config:
<object id="ClassAInstance" type="ClassA, Blah"> ... </object>
<object id="ClassBInstance" type="ClassB, Blah"> ... </object>
Now some generalized sample code using the WebApplicationContext:
IApplicationContext context = new XmlApplicationContext(locations);
IClass c = (IClass)context.GetObject(declarationId);
There are a couple of things to note:
- Pass in the id of the declaration you wish to use not the Type name, so the variable declarationId would have the value of either "ClassAInstance" or "ClassBInstance".
- The constructor to XmlApplicationContext (and WebApplicationContext) takes a parameter of an array of string values; the variable locations would be an array of configuration resources to search through to find the object with id declarationId. You cannot use a generic List here, it has to be an actual string array.
One interesting implication of point 2 above is that you actually control which configuration resources your ApplicationContext is aware of: when you call the GetObject() method, the ApplicationContext will only search for your object within the configuration resources given in the array locations[]. This means that rather than list all possible configurations within one file each with a unique id, you can have multiple configuration resources instead, each containing one object declaration and each with the same id:
Config1.xml: <object id="IClassInstance" type="ClassA, Blah"> ... </object>
Config2.xml: <object id="IClassInstance" type="ClassA, Blah"> ... </object>
But when instantiating the object, you can control which object is created not based on the declarationId, which in both cases will be "IClassInstance", but by changing the locations[] array to contain the configuration resource you want to use, in this case either Config1.xml or Config2.xml
Hope this is of use,
Andrew