你的位置:首页 > 软件开发 > ASP.net > MEF入门之不求甚解,但力求简单能讲明白(五)

MEF入门之不求甚解,但力求简单能讲明白(五)

发布时间:2016-05-30 11:00:04
我们已经成功的达到了目标,大量减少了if else。不过在园子里面的文章大多,用的是Import、ImportMany。So,修改主函数。using IPart;using System;using System.Collections.Generic;using System. ...

MEF入门之不求甚解,但力求简单能讲明白(五)

我们已经成功的达到了目标,大量减少了if else。

不过在园子里面的文章大多,用的是Import、ImportMany。So,修改主函数。

using IPart;using System;using System.Collections.Generic;using System.ComponentModel.Composition;using System.ComponentModel.Composition.Hosting;using System.Linq;namespace meftest{  class Program  {    [ImportMany]    private IEnumerable<Lazy<IFileHandler, IPatMetadata>> fileHandlers;//警告,说没有赋值过。不用理会,MEF会自己导入的。    static void Main(get='_blank'>string[] args)    {      //模拟数据。      string[] files = new string[] {        @"c:\xxoo\xxoo.txt",        @"c:\xxoo\ooxx.doc",        @"d:\测试目录\mm.jpg",        @"e:\电影\天海翼.avi",      };      Program p = new Program();      p.Compose();      foreach (var file in files)      {        string ext = System.IO.Path.GetExtension(file).ToLower();        var export = p.fileHandlers.SingleOrDefault(o => o.Metadata.Extension == ext);//根据扩展名,也就是元数据来找到对应的处理实例        if (export != null)          export.Value.Process(file);      }      Console.ReadLine();    }    private void Compose()    {      //AssemblyCatalog 目录的一种,表示在程序集中搜索      var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly);//此处这一句实际上没啥用,因为此程序集下没有任何我们需要的实例(各种handler)      //在某个目录下的dll中搜索。      var directoryCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "*.dll");      var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog);//聚合目录包含有2种搜索方式      var container = new CompositionContainer(aggregateCatalog);      container.ComposeParts(this);//将部件组合在一起。意思就是将所有Export的部件,装配到this实例中标记为Import、ImportMany的属性上。    }  }}

原标题:MEF入门之不求甚解,但力求简单能讲明白(五)

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录