I have 2 classes both inherit from the same interface. i want sometimes to run the website using one class and sometimes with another one. Want to decide which one to use based on a configuration value. Can i use web.config to decide which class to create the current instance from?
+3
A:
Yes.
Create a factory method that returns an object of type IMyInterface
. Pass in the config value as a parameter to determine which concrete object to create.
IMyInterface FactoryMethod(string configValue)
Mitch Wheat
2009-09-11 02:58:22
This is the right idea which will help me.
Amr ElGarhy
2009-09-11 03:05:32
+1
A:
Indeed you can. Of interest to you is the field AssemblyQualifiedName
of Type
. So get your type and do:
myObj.GetType().AssemblyQualifiedName
And write the result of this into your config:
<add key="TypeName" Value="...." />
Then, you'll need to consider what constructors it has, and it can be loaded like so:
Type.GetType("...").GetConstructor(...).Invoke(...);
Noon Silk
2009-09-11 02:59:45
No worries Mitch, I'm guessing it was the OP given his comment to you :)
Noon Silk
2009-09-11 03:07:12
voting up, as it could of been the right answer depending how the original question was interpreted
Mitch Wheat
2009-09-11 03:07:28
wasn't me as well, i didn't try your solution yet, just found Mitch answer simple and understood very fast, also will try yours
Amr ElGarhy
2009-09-11 03:08:52
Amr: They're both kind of the same anyway. Mitch's is probably a better way to abstract out the creation of the types (I haven't told you how to do that in mine), but either way you may be creating the types reflectively, or not, and for a reflective-create you can use the info I've provided to help figure out how. The answer you have accepted is probably the most appropriate. All good.
Noon Silk
2009-09-11 03:12:12