views:

27

answers:

2

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
This is the right idea which will help me.
Amr ElGarhy
+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
btw, that downvote wasn't me...
Mitch Wheat
No worries Mitch, I'm guessing it was the OP given his comment to you :)
Noon Silk
voting up, as it could of been the right answer depending how the original question was interpreted
Mitch Wheat
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
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
Yes, i understood, thanks for your answer and clarification
Amr ElGarhy