MEF学习(一) ----- MEF介绍

.NET 4.0引入了一个“Managed Extensibility Framework(MEF”,郑重推荐!MEF通过简单地给代码附加“[Import]”和“[Export]”标记,我们就可以清晰地表明组件之间的“服务消费”与“服务提供”关系,MEF在底层使用反射动态地完成组件识别、装配工作。从而使得开发基于插件架构的应用系统变得简单。够酷的技术!

 

先来看看从codeproject上下载回来的一个非常简单的例子。解决方案的名字叫 HelloMEFWorld!其结构如下图所示:

image

本解决方案中,有如上图中所示的一个IPerson接口,两个实现了此接口的类:Customer和Employee。他们的代码分别如下所示:

IPersion:

 1: public interface IPerson
 2: {
 3:  void WriteMessage();
 4: }
 

Customer:

 1: [Export(typeof(IPerson))]
 2: public class Customer : IPerson
 3: {
 4:  public void WriteMessage()
 5:  {
 6:  Console.WriteLine("I am your Customer");
 7:  Console.ReadLine();
 8:  }
 9: }

 

Employee:

 1: [Export(typeof(IPerson))]
 2: public class Employee : IPerson
 3: {
 4:  public void WriteMessage()
 5:  {
 6:  Console.WriteLine("I am your Employee");
 7:  Console.ReadLine();
 8:  }
 9: }
 
如上面的代码所示,Customer与Employee类使用ExportAttribute特性对外导出IPerson接口。那么,此接口导出后,我们又该如何去使用呢? 参见如下的代码:
 1:  public class Program
 2:  {
 3:  [ImportMany]
 4:  public IPerson[] Persons { get; set; }
 5:  
 6:  static void Main(string[] args)
 7:  {
 8:  Program p = new Program();
 9:  
 10:  p.ListAllPersons();
 11:  }
 12:  
 13:  private void ListAllPersons()
 14:  {
 15:  CreateCompositionContainer();
 16:  
 17:  foreach (var person in Persons)
 18:  {
 19:  person.WriteMessage();
 20:  }
 21:  }
 22:  
 23:  private void CreateCompositionContainer()
 24:  {
 25:  AssemblyCatalog catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
 26:  CompositionContainer compositionContainer = new CompositionContainer(catalog);
 27:  compositionContainer.ComposeParts(this);
 28:  }
 29:  }
 
 
如上面的代码所示,在Program类中定义了一个属性Personer集合声名了一个导入特性: ImportManyAttibute。此特性的作用是将本程序集中所有标识有导出特性的IPerson接口的类全部存放到Person集合中。
 
 
通过这一篇文章,了解到了Export与Import之间的含义:
Export  是导出的意思,指示被标记过的对象将被系导出,供其他组件使用。
Import  是导入的意思,指示意被标记的元素将由系统自动导入可以匹配的项。

你可能感兴趣的:(学习)