創建插件框架(1)
2024-07-21 02:17:13
供稿:網友
 
創建插件框架(1)
標題:create a plug-in framework
作者:roy osherove
譯者:easyjoy
出處:msdn online,鏈接為
http://msdn.microsoft.com/asp.net/archive/default.aspx?pull=/library/en-us/dnaspp/html/pluginframework.asp
摘要:介紹如何為.net應用程序添加插件支持,并提供一個框架例子。
 
代碼下載:鏈接為
http://download.microsoft.com/download/7/2/e/72e64769-58d2-4a91-9686-a1a160bb1bc8/createpluginframework.msi
 
目錄
應用程序為什么需要插件框架
第一步:創建簡單文本編輯器
第二步:創建plug-in sdk
第三步:創建自己定制的插件
第四步:讓應用程序找到新插件
第五步:用iconfigurationsectionhandler解析配置文件
實例化并調用插件
調用插件
總結
 
應用程序為什么需要插件框架
出于以下原因,人們通常為應用程序添加插件支持:
(1)在不需要重新編譯和發布程序的情況下擴展功能;
(2)在不訪問源代碼的情況下添加新功能;
(3)應用程序業務規則變化頻繁,或者經常有新的規則要加進來;
 
本文將構造一個簡單的文本編輯器,該編輯器只有一個窗口。該程序唯一的功能就是在窗體中間的編輯框中顯示一行文本。這個程序編好后,我們開始為它創建一個簡單插件;這個插件讀出編輯框中的文本,解析出其中的有效的email地址,然后返回該email。
 
如上所述,,這個例子中我們面臨如下未知因素:
(1)應用程序本身如何找到插件;
(2)插件如何知道文本編輯框中的內容;
(3)如何激活插件;
 
第一步:創建簡單文本編輯器
詳細操作此處省略。下載的源代碼中已經包含它。從此處開始,我假設你已經創建了這個簡單程序。
 
第二步:創建plug-in sdk
現在已經構造了程序,如何讓應用程序與外邊插件交流呢?怎樣讓它們交流呢?
 
解決方法是應用程序發布一個接口,所有的插件都要實現接口中的公共成員和方法。此處假設這個接口是iplugin,所有想開發插件的開發人員都必須實現這個接口。這個接口位于共享庫(shared library)中,應用程序和插件都用到它。下面是接口的定義:
 
public interface iplugin
{
 string name{get;}
 void performaction(iplugincontext context);
}
 
這段代碼很容易懂,但是為什么要給performaction一個iplugincontext接口呢?原因在于這相對于直接把字符串當作參數進行傳遞,傳遞接口可以有更多的靈活性。目前,iplugincontext接口非常簡單:
 
public interface iplugincontext
{
 string currentdocumenttext{get;set;}
}
 
現在所要做的就是在若干對象中實現接口,并把對象傳遞給插件,并獲取結果。這使得將來可以不僅修改文本框,還可以修改任何對象。
 
第三步:創建自己定制的插件
現在要做的是
(1)創建一個單獨的類庫對象;
(2)創建一個類實現接口iplugin;
(3)編譯并放到主程序同一目錄下;
 
public class emailplugin:iplugin
{
 public emailplugin()
 {
 }
 // the single point of entry to our plugin
 // acepts an iplugincontext object
// which holds the current
 // context of the running editor.
 // it then parses the text found inside the editor
 // and changes it to reflect any 
// email addresses that are found.
 public void performaction(iplugincontext context)
 {
 context.currentdocumenttext=
 parseemails(context.currentdocumenttext);
 }
 
 // the name of the plugin as it will appear 
 // under the editor's "plugins" menu
 public string name
 {
 get
 {
 return "email parsing plugin";
 }
 }
 
 // parse the given string for any emails using the regex class
 // and return a string containing only email addresses
 private string parseemails(string text)
 {
 const string emailpattern= @"/[email protected]/w+/./w+((/./w+)*)?";
 matchcollection emails = 
 regex.matches(text,emailpattern,
 regexoptions.ignorecase);
 stringbuilder emailstring = new stringbuilder();
 foreach(match email in emails)
 {
 emailstring.append(email.value + environment.newline);
 }
 
 return emailstring.tostring();
 }
}
 
未完待續
剩下部分參見http://www.csdn.net/develop/read_article.asp?id=26339
網站運營seo文章大全提供全面的站長運營經驗及seo技術!