In the previous article, we know that the hostProgramDefines a protocol for the plug-in program to communicate with the plug-in program. The plug-in is unbalanced. Sometimes I also need to know some information about your host Program to complete my work. Therefore, I must communicate with you and have the right to have a conversation. In fact, plug-ins generally use the context of the Host Program more or less. For example, the vs plug-in needs to obtain the editedCodeObject to complete its work, such as formatting, statistics, and the player's lyrics plug-in. At least you need to obtain which song the player is playing. So how can we implement this communication? We know that the host uses an interface to operate the plug-in. Similarly, the plug-in can use an interface to operate the host. First, we need to specify the attributes and methods provided by the host for operations by the plug-ins. We can extract an interface to regulate these actions. This interface is the bridge between the plug-in and the host context. As long as the plug-in holds a reference to this interface and assigns a reference to the Host Program during instantiation, the plug-in has the right to talk. Slightly change the previous Code, as shown below:
Add a contract that the host must implement:
1 Public Interface Iappcontext
2 {< br> 3 // specify that the Host Program has a string attribute
4 string texttoprint { Get ; set ;}
5 }
Modify the plug-in interface so that the interface has a reference to it.
1 Public Interface Iplugin
2 {
3 Iappcontext app { Get ; Set ;}
4 // Print things on the console. Here you can write any contractual actions you want.
5 Void Printtoconsole ();
6 }
The host program implements iappcontext
1 Public Class Simpleplugin: iappcontext
2 {
3 String _ Textout = " This is a property of the main program " ;
4 Public String Texttoprint
5 {
6 Get { Return _ Textout ;}
7 Set {_ Textout = Value ;}
8 }
9 ......
10 }
In the next step, when instantiating the plug-in, we will assign reference to the local program. Here I will pull the plug-in and instantiate the plug-in to a specific class, because this cannot be used in static methods to use the iappcontext reference in the current host Program initialization plug-in
1 Foreach (System. Type type In Types)
2 {
3 // Check whether the loaded dll has implemented the contract. attribute can also be used here.
4 If (Type. getinterface ( " Iplugin " ) ! = Null )
5 {
6 Iplugin plugin = (Iplugin) activator. createinstance (type );
7 Plugin. app = This ;
8 Plugs. Add (plugin );
9 }
10 }
In this way, the properties exposed by the Host Program can be accessed in the plug-in.
1 // Implements the methods agreed in contract, and outputs The textout string of the Host Program on the console.
2 Public Void Printtoconsole ()
3 {
4 Console. writeline (m_app.texttoprint );
5 }
The result is as follows:
Code download: http://files.cnblogs.com/Pcant/simplePlun-in2.rar