Using reflection in. NET to implement a simple plug-in mechanism

Source: Internet
Author: User

This is my study of reflection of the application of a small scene and do the study notes, mainly a small summary, and the individual steps of the record for future review.

I. Basic framework-Agile basic version

This assumes that we are going to develop a Notepad, choose Windows Form Technology development, as shown in the interface:

The Notepad only provides a textbox for input, and saves it to the specified file. Other features are not implemented, assuming that we first make this version, the subsequent function through the plug-in form step by step completion.

However, to be able to use the plugin, our main project has to undergo some modifications:

(1) need to get plug-ins from the plug-in directory when loading

     PublicFormMain () {InitializeComponent (); //Loading PluginsLoadplugins (); }    Private voidLoadplugins () {//1. Load all DLL files in the plugins directory        stringPlugins = Path.Combine (Path.getdirectoryname (assembly.getexecutingassembly (). Location),"Plugins"); //1.1 Search All DLL files in the plugins directory        string[] dlls = Directory.GetFiles (Plugins,"*.dll"); //2. Loop to load each DLL file        foreach(stringDllPathinchDLLs) {            //2.1 Dynamically loading DLL files for the current loopAssembly Assembly =Assembly.loadfile (DllPath); //2.2 Gets all the public types in the current DLLtype[] Types =Assembly.            Getexportedtypes (); //2.3 Getting the type of the Ieditor interfaceType Typeieditor =typeof(Ieditor);  for(inti =0; I < types. Length; i++)            {                //2.4 Verify that the current type implements the Ieditor interface and that the type can also be instantiated                if(Typeieditor.isassignablefrom (types[i]) &&!Types[i]. IsAbstract) {Ieditor Editor=(Ieditor) activator.createinstance (Types[i]); //2.5 Adding a menu item dynamically to the menus barToolStripItem Toolitem =ToolstripEditMenu.DropDownItems.Add (editor.                    Pluginname); //2.6 Registering a click event for the newly added menu itemToolitem.click + =NewEventHandler (Toolitem_click); Toolitem.tag=Editor; }            }        }    }

(2) Set a generic click event for the plugin

    Private voidToolitem_click (Objectsender, EventArgs e) {ToolStripItem Item= Sender asToolStripItem; if(Item! =NULL)        {            if(item. Tag! =NULL) {Ieditor Editor= Item. Tag asIeditor; if(Editor! =NULL)                {                    //Run the pluginEditor. Execute ( This. txtcontent); }            }        }

It is agreed that all plug-ins implement the Ieditor interface, and that all plug-in functions are implemented in the Execute method.

Ii. agreed interfaces-a scalable foundation

It is not difficult to find that if we call the DLL directly using reflection , even if we find the DLL file, we do not know what the function is called, even if it can be enumerated, it is not possible to intelligently invoke the function inside, to achieve our expected function extension. So we are puzzled, we have written the program can expect to call which DLLs later which function?

In fact, this is not complicated, we can use interface technology to achieve such a function. The so-called interface, is a protocol, when you write a DLL to abide by such a protocol, then we write the DLL can be conveniently called by EXE.

For this little demo, we design a Ieditor interface as follows:

     Public Interface Ieditor    {        string  pluginname        {            get;        }         void Execute (TextBox txtbox);    }

Where Pluginname is the name of the plugin for the menu display. The Execute method receives a TextBox control for Notepad, which is used to implement specific functions.

Third, the implementation of plug-in-upgradeable features

(1) Plug-in 1: Convert all text to uppercase

Create a new class library project and design a class that implements the Ieditor interface:

     Public classChangefontstyle:ieditor { Public stringPluginname {Get            {                return "Convert to uppercase"; }        }         Public voidExecute (TextBox txtbox) {if(!string. IsNullOrEmpty (Txtbox. Text) {Txtbox. Text=Txtbox.            Text.toupper (); }            Else{MessageBox.Show ("Please enter the text first! "); }        }

(2) Plugin 2: Turn text all red

Create a new class library project and design a class that implements the Ieditor interface:

     Public classChangefontcolor:ieditor { Public stringPluginname {Get            {                return "Change Color"; }        }         Public voidExecute (TextBox txtbox) {if(!string. IsNullOrEmpty (Txtbox. Text) {Txtbox. ForeColor=System.Drawing.Color.Red; }            Else{MessageBox.Show ("Please enter the text first! "); }        }    }
Iv. embracing change-a simple test

(1) Notepad program without any plugins

Plugins Plugin Directory The next DLL also has wood:

So our Notepad has only the most basic operations:

(2) Add plugin 1 (convert uppercase) Notepad program

The Plugins plugin directory has a DLL:

This adds the ability to convert uppercase:

(3) Add plugin 2 (change color) Notepad program

The Plugins plugin directory has two DLLs:

This adds the ability to change colors:

So, with the reflection and interface, we can customize the plug-in to implement different extensions to make our main software project more powerful!

Zhou Xurong

Source: http://edisonchou.cnblogs.com

The copyright of this article is owned by the author and the blog Park, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to give the original link.

Using reflection in. NET to implement a simple plug-in mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.