views:

90

answers:

2

I have an application that uses plugins that are managed via an interface I then dynamically load the plugin classes and cast them to the interface to work with them.

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

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

This should be pretty simple, create the instance and cast it to the interface. I know that the assembly and fully qualified name values are correct, but I am getting the following exception.

Exception= System.InvalidCastException: Unable to cast object of type ‘System.Runtime.Remoting.ObjectHandle’ to type ‘MyNamespace.Components.Integration.IPlugin’. at MyNamespace.Components.Integration.PluginProxy..ctor(Int32 instanceId)

Any ideas what could cause this?

+1  A: 

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

The ObjectHandle cannot be casted directly to your interface.
Instead, you need to call the Unwrap method, like this:

IPlugin _plugin = (IPlugin)Activator.CreateInstance(...).Unwrap();
SLaks
Won't he need to cast to `ObjectHandle` first, in order to `Unwrap()`?
Jay
@Jay: No; it's declared as returning `ObjectHandle`. Read the documentation.
SLaks
+3  A: 

The exception indicates that you're getting an ObjectHandle, which suggests that your object is being marshaled and must be unwrapped.

Try the following

ObjectHandle marshaled_plugin = (ObjectHandle)Activator.CreateInstance(oInfo.Assembly,  Info.FullyQualifiedName);
IPlugin plugin = (IPlugin)marshaled_plugin.Unwrap();
Jay
Thanks! That fixed it
Mitchel Sellers