Reputation: 5124
In all of the examples of Spring.NET IoC, I see something like this:
interface IClass;
class ClassA : IClass;
class ClassB : IClass,
And then in the config.xml file, something like:
[object id="IClass" type="ClassB, Spring.Net.Test" /]
But I really need to do something like this in the config file where there will be multiple implementations if interface:
[object id="IClass" type="ClassA, Blah" /]
[object id="IClass" type="ClassB, Blah" /]
And then in _runtime_
I choose from them. Something like this:
IClass c = [get me all implementations of IClass, and choose the one with
GetType().FullName == myVariableContainingFullTypeNameOfObjectIWant]
How can I do something like this?
Many thanks!
Upvotes: 1
Views: 951
Reputation: 1069
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:
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
Upvotes: 1
Reputation: 5194
maybe you could try this:
[object id="Blah.ClassA" type="ClassA, Blah" /]
[object id="Blah.ClassB" type="ClassB, Blah" /]
IClass = (IClass) ApplicationContext.GetObject(myVariableContainingFullTypeNameOfObjectIWant);
Upvotes: 0