I have a requirement of loading assembly of different version(I already have the assembly with same name in my application).
I was able to load the assembly and load the method i need to invoke using reflection but when i go to invoke the method by passing my class object as argument, i got the exception that class object cannot be converted to the type of argument parameter.
Sample Code -
Assembly myAssembly = Assembly.LoadFrom("Assembly Path for assembly with different version");
object classObject = myAssembly.CreateInstance("ClassName");
Type classType = myAssembly.GetType("ClassName");
MethodInfo myMethod = classType.GetMethod("MyMethod", BindingFlags.Instance);
// Creating an object of class in the latest assembly and need to pass this
// to method in assembly with different version.
ClassInBothVesions parameter = new ClassInBothVesions();
myMethod.Invoke(classObject, new object[] { parameter });
Here parameter is an object of a class which i have in assembly but since parameter class is created in the assembly of the current version. And when i try to pass it to the method of previous assembly, i got an exception that it cannot be converted.
How can i achieve this? Let me know in case if i need to put on some more information here. Thanks in advance.
You should check out the Managed Extensibility Framework (MEF). It makes doing what you want to do much easier and abstracts you away from having to worry about AppDomains and different assemblies.
Edit:
If you wish to use reflection only to achieve what you want, it'll require a flexible object model within your application. The basics of this approach is what MEF kind of does underneath the hood. Where you really get the power to do this is from .Net remoting, so I'd suggest you read up on that.
What you'll need:
Your application in (assembly A).
Assembly with old class code (assembly C).
A Remote Loader class that will act as your proxy/remote to the second AppDomain.
A proxy class that will represent an instance of the old version of a class.
Assembly B which will contain your proxy class and your remote loader.
Here's what you could try:
Load application from assembly A.
Create new AppDomain instance.
Instantiate an instance of your "Remote Loader" class in the new AppDomain from assembly B.
a. This will cause assembly B to be loaded into the AppDomain.
From your "Remote Loader", load assembly C and instantiate your old class then pass back an instance of the proxy class to the original AppDomain.
Now hopefully you can modify your methods to accept a more generic version of the object (possibly an interface?) that the proxy and your new class version can both implement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With