在文章開始以前,首先簡單介紹一下什麼是MEF,MEF,全稱Managed Extensibility Framework(託管可擴展框架)。單從名字咱們不難發現:MEF是專門致力於解決擴展性問題的框架,MSDN中對MEF有這樣一段說明:html
Managed Extensibility Framework 或 MEF 是一個用於建立可擴展的輕型應用程序的庫。 應用程序開發人員可利用該庫發現並使用擴展,而無需進行配置。 擴展開發人員還能夠利用該庫輕鬆地封裝代碼,避免生成脆弱的硬依賴項。 經過 MEF,不只能夠在應用程序內重用擴展,還能夠在應用程序之間重用擴展。編程
廢話很少說了,想了解更多關於MEF的內容,到百度上面查吧!框架
MEF的使用範圍普遍,在Winform、WPF、Win3二、Silverlight中均可以使用,咱們就從控制檯提及,看看控制檯下如何實現MEF,下面先新建一個win32控制檯項目MEFDemo,添加一個IBookService接口,寫一個簡單的Demo:post
IBookService內容以下:學習
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace MEFDemo { public interface IBookService { string BookName { get; set; } string GetBookName(); } }
下面添加對System.ComponentModel.Composition命名空間的引用,因爲在控制檯程序中沒有引用這個DLL,因此要手動添加:this
點擊OK,完成添加引用,新建一個Class,如:MusicBook繼承IBookService接口,代碼以下:spa
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel.Composition; namespace MEFDemo { [Export(typeof(IBookService))] public class MusicBook : IBookService { public string BookName { get; set; } public string GetBookName() { return "MusicBook"; } } }
Export(typeof(IBookService)) 這句話將類聲明導出爲IBookService接口類型。code
而後修改Porgram中的代碼以下:orm
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; namespace MEFDemo { class Program { [Import] public IBookService Service { get; set; } static void Main(string[] args) { Program pro = new Program(); pro.Compose(); if (pro.Service != null) { Console.WriteLine(pro.Service.GetBookName()); } Console.Read(); } private void Compose() { var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly()); CompositionContainer container = new CompositionContainer(catalog); container.ComposeParts(this); } } }
這裏使用[Import]導入剛剛導出的MusicBook,下面的Compose方法,實例化CompositionContainer來實現組合,點擊F5運行,結果以下:htm
能夠看到調用了MusicBook類的GetBookName方法,可是咱們並無實例化MusicBook類,是否是很神奇呢???
這一就是實現了主程序和類之間的解耦,大大提升了代碼的擴展性和易維護性!
MEF系列文章:
C#可擴展編程之MEF學習筆記(一):MEF簡介及簡單的Demo