Casting error with reflection

I have an application that uses plugins that are controlled through an interface. Then I dynamically load the plugin classes and pass them to the interface to work with them.

I have the following line of code, suppose IPlugin is my interface.

IPlugin _plugin = (IPlugin)Activator.CreateInstance(oInfo.Assembly, oInfo.FullyQualifiedName) 

It should be pretty simple, instantiate and pass it to the interface. I know that the assembly and fully qualified name values ​​are correct, but I get the following exception.

Exception = System.InvalidCastException: cannot cast object of type "System.Runtime.Remoting.ObjectHandle print" MyNamespace.Components.Integration.IPlugin. in MyNamespace.Components.Integration.PluginProxy..ctor (Int32 InstanceId)

Any ideas what might cause this?

+7
reflection c # interface
source share
2 answers

An exception indicates that you are getting an ObjectHandle , which assumes that your object is marshaled and needs to be expanded.

Try to execute

 ObjectHandle marshaled_plugin = (ObjectHandle)Activator.CreateInstance(oInfo.Assembly, Info.FullyQualifiedName); IPlugin plugin = (IPlugin)marshaled_plugin.Unwrap(); 
+12
source share

As you can see in the documentation , this overload returns an ObjectHandle object that wraps the new instance.

ObjectHandle cannot be sent directly to your interface.
Instead, you need to call the Unwrap method:

 IPlugin _plugin = (IPlugin)Activator.CreateInstance(...).Unwrap(); 
+7
source share

All Articles