If you have used some excellent open-source or non-open-source application software, you will find that a major advantage of these software is its openness, anyone with the ability can develop different plug-ins for them to enhance their functions. For example, the famous foobar2000, Vim and TotalCommander.
C # reflection can be used to implement a Simple plug-in system. The idea is simple. We create a solution that contains three projects, one for our software MyApplication, the other for the plug-in interface IPlugin, and the other for the specific plug-in MyPlugin. The basic idea of the plug-in system is to use an interface class library to define the method signature that must be implemented by the plug-in that can be used by our software. Then, our software MyApplication dynamically calls by referencing the IPlugin dll, and the specific implementation plug-in MyPlugin references this interface to implement specific methods. In this way, our application can call the plug-in without knowing the specific plug-in ..
The structure is as follows:
The key code is load the assembly. Find the implementation class of the corresponding interface. Then you can call it.
Assembly a = Assembly. LoadFrom (AssemblyName); foreach (Type t in a. GetTypes () {if (t. GetInterface ("IMyFunction ")! = Null) {try {IMyFunction pluginclass = Activator. createInstance (t) as IMyFunction; pluginclass. doSomething ();} catch (Exception ex) {MessageBox. show (ex. toString ());}}}
Running result:
Source code download: PluginSystem.zip