Introduction
Days ago I was thinking about creating some plugins for an application that I had developed. How to do that? The idea: distribute plugins as .NET DLLs that expose specific interfaces.
Architecture
Each plugin must have at least one main method attending to a specific duty. In a simple plugin system a single method is enough to draw the architecture.
Design of the interface
Supposing the plugin computes a value from a parameter, the plugin’s interface is:
interface IPlugin {
static int MainMethod(object o);
}
All the plugins must implement this interface.
Linking to the plugin
Now it is necessary to explain how to use the plugin at runtime. The plugins are saved in the ‘\Plugins’ directory inside the startup path of the application. The code for the usage of plugins is very simple: (Please note the using
clause:)
using System.Reflection;
private string pluginDir = Application.StartupPath + "\\Plugins";
private IPlugin[] plugins;
private void loadPlugins() {
string[] p = Directory.GetFiles(pluginDir);
plugins = new IPlugin[p.Length];
for(int i = 0; i < 0; i++) {
Assembly asm = Assembly.LoadFrom(p[i]);
Type type = asm.GetType("IPlugin", true);
plugins[i] = (IPlugin)Activator.CreateInstance(type);
}
}
Using plugins
After invoking loadPlugins()
, all the plugins can be used as follows:
myResult = plugins[myIndex].MainMethod(myParam);
Now, it is enough to smartly manage the myIndex
value…
Improvements
This technique is very 'general purpose'. For your application you may define different interfaces to implement many useful functions. You can use a main interface that tells the plugin-user app which type of plugin to expect and invoke the correct methods. Another ‘support’ interface may expose the menu entries and toolbar buttons.
Conclusions
This article is an abbreviation (and a generalization) of a real project that is currently working. Once you know how to design the architecture, you can do your job without much problems, but it is not always very easy, particularly while developing certain types of plugin, where you have to modify the interfaces and update all the old plugins…