I am trying to implement a plugin system in C#, and for that I created the following classes and interfaces:
Included in both loader and plugin:
interface IDevicePlugin {
string GetName();
string GetVersion();
}
Plugin code (compiles to .dll)
public class DummyPlugin : IDevicePlugin {
protected string name;
protected string version;
public string GetName() {
return name;
}
public string GetVersion() {
return version;
}
}
The code to load the plugin is as follows:
IDevicePlugin thePlugin;
Assembly plugin = Assembly.LoadFrom("plugin.dll");
foreach (Type pluginType in plugin.GetTypes()) {
if (pluginType.IsPublic && !pluginType.IsAbstract) {
Type typeInterface = pluginType.GetInterface("IDevicePlugin", true);
if (typeInterface != null) {
// the plugin implements our IDevicePlugin interface
thePlugin = (IDevicePlugin)Activator.
CreateInstance(plugin.GetType(pluginType.ToString()));
}
}
}
And this crashes with:
Unable to cast object of type 'PluginTest.DummyPlugin' to type 'PluginTest.IDevicePlugin'.