在文章开始以前,首先简单介绍一下什么是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