星空网 > 软件开发 > ASP.net

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

在上一篇文章中,我们已经学到了很基本的MEF概念和使用方法。

但我们导出的是一个object类型的实例,只能用来tostring,没有引用部件类库,也不能用里面的成员方法。

本篇,我们逐渐往简单的文件管理器的目标靠拢。

新建类库IPart,添加一个接口IFileHandler.cs

namespace IPart{  public interface IFileHandler  {    void Process();  }}

Parts类库和主项目meftest均引用IPart

Parts类库中,将要导出的类型改为IFileHandler,类实现IFileHandler

以其中一个为例。

using IPart;using System;using System.ComponentModel.Composition;namespace Parts{  [Export(typeof(IFileHandler))]//表示此类需要导出,导出的类型为IFileHandler  public class TxtFileHandler: IFileHandler  {    public void Process()    {      Console.WriteLine("处理文本文件");    }  }}

主项目:

using IPart;using System;using System.ComponentModel.Composition.Hosting;namespace meftest{  class Program  {    //容器,装东西用的。具体装什么先不管。    private static CompositionContainer container;    static void Main(string[] args)    {      //AssemblyCatalog 目录的一种,表示在程序集中搜索      var assemblyCatalog = new AssemblyCatalog(typeof(Program).Assembly);//此处这一句实际上没啥用,因为此程序集下没有任何我们需要的实例(各种handler)      //在某个目录下的dll中搜索。      var directoryCatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory,"*.dll");      var aggregateCatalog = new AggregateCatalog(assemblyCatalog, directoryCatalog);      //创建搜索到的部件,放到容器中。      container = new CompositionContainer(aggregateCatalog);          var exports = container.GetExports<IFileHandler>();//获得所有导出的部件(IFileHandler类型的)。      foreach (var item in exports)      {        item.Value.Process();//此处已经可以调用IFileHandler.Process()了      }      Console.ReadLine();    }  }}

编译后,别忘了把Parts.dll拷贝到主程序的bin\debug下。

运行:

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

我们已经把所有IHandler类型的实例创建出来了,并且运行了其中的成员函数。

 最恨天下文章一大抄,请不要转载。




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

关键词:

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

千合跨境物流:https://www.goluckyvip.com/tag/92711.html
中欧跨境物流:https://www.goluckyvip.com/tag/92713.html
羊驼帮跨境物流:https://www.goluckyvip.com/tag/92714.html
鸿桥跨境物流:https://www.goluckyvip.com/tag/92715.html
云途跨境物流:https://www.goluckyvip.com/tag/92716.html
鸿泰信跨境物流:https://www.goluckyvip.com/tag/92717.html
你更喜欢一个人旅行,还是一群人旅行? :https://www.vstour.cn/a/408249.html
延安市区景点都收费吗 延安景点要门票吗:https://www.vstour.cn/a/408250.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流