Reputation: 891
I have an application that has a series of service references that change almost monthly. Most times the changes are minimal if any are present at all. I want to be able to select which reference to use at runtime depending on the version being targeted in a config file. For example. I may have three versions of the below NameSpace which all have Class1. Class1 may have a minor change between versions like an additional property. Any guidance would be helpful :)
NameSpaceVersion1.Class1 MyVar = new NameSpaceVersion1.Class1();
NameSpaceVersion2.Class1 MyVar = new NameSpaceVersion2.Class1();
NameSpaceVersion3.Class1 MyVar = new NameSpaceVersion3.Class1();
Upvotes: 0
Views: 1348
Reputation: 26
What you seem to be looking for is Assembly.LoadFrom(filepath/binary) see msdn and create you configured instances using Activator.CreateInstance() see msdn.
Upvotes: 0
Reputation: 46219
If those three namespace in the same DLL
You can try to use Activator.CreateInstance
with Type.GetType
function.
Type.GetType(nameSapce)
get class type with namespace in this DLLActivator.CreateInstance
reflation create a object.like this.
string nameSapce = ConfigurationManager.AppSettings["NameSpace"];
var MyVar = Activator.CreateInstance(Type.GetType(nameSapce));
Setting on webConfig
key NameSpace
can set which class you want to create on runtime.
<configuration>
<appSettings>
<add key="NameSpace" value="NameSpaceVersion2.Class1"/>
</appSettings>
</configuration>
Upvotes: 1
Reputation: 12780
This is a good use for interfaces.
However, if you cannot change the implementation (so each class implements the interface), you can create wrapper classes that do so.
Basically, create a class for each implementation that implements the target interface, but passes calls to the target implementation. You would pass the implementation class to the wrapper class in the constructor and then store it as a private field that would be used for each public member access of the interface.
Upvotes: 0