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'.
The interface exists twice:
Once in your plugin.dll and once in your loader.
The reason is that you added a reference (=link) to the *.cs file containing the interface definition to the plugin project. Additionally, the same *.cs file is part of the loader project.
Because of that, the interface gets compiled into both assemblies. These are two different interfaces, even when they are named the same!
To fix this problem, you should do the following:
Either add a reference for the Loader project to the plugin project
– OR –
Create a new project for the interface and reference this project from both the loader and the plugin projects.