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

时间:2023-03-08 21:58:30

在上一篇文章中,我们已经学到了很基本的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类型的实例创建出来了,并且运行了其中的成员函数。

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