[MEF] 学习之一 入门级的简单Demo

MEF 的精髓在于插件式开发,方便扩展。

我学东西,习惯性的先搞的最简单的Demo出来,看看有没有好玩的东东,然后继续深入。这个博文,不谈大道理,看demo说事儿。

至于概念,请google ,大把大把的。

例如,应用程序的日志输出到文本,后来想改为输出到数据库,按照传统的办法,需要替换项目,删除原有的引用,增加新的引用;如果使用MEF,直接用新的dll替换原来的dll,即可搞定,这就是MEF的魅力。

下面就用简单的例子来实现上述的需求。

1. 建立一个解决方案,然后增加如下的几个项目

Dblog 输出日志到数据库的实现

TextLog 输出日志到文本的实现

Ilog 输出日志的接口,调用方和实现者的中间桥梁

MEFConsoleHost 控制台应用程序,模拟实用场合

MEFWPFHost WPF 应用程序,模拟实用场合

2. 先定义接口Ilog,非常简单,就一个方法

3.  输出到文本的实现TextLog

首先添加引用:引用刚才添加的接口Ilog 和System.ComponentModel.Composition

然后增加类TextLogService.cs,继承接口,并实现方法。

注意 类和方法都Public。

最后定义导出[Export(typeof(ILog.ILogService))]

这个是最主要的,和普通的类库区别也在这里

4. 输出到数据库的实现DbLog,实现方法同上例,输出日志的时候区分一下。

5. 调用方MEFConsoleHost, 这个也需要增加两个引用,

Ilog 和System.ComponentModel.Composition

主程序代码如下:

class Program

{

[Import(typeof(ILogService))]

public ILogService CurrentLogService { get; set; }



static void Main(string[] args)

{

Program pro = new Program();

pro.Run();

}



void Run()

{

//var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory,"DbLog.dll");

var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "TextLog.dll");



var container = new CompositionContainer(catalog);

container.ComposeParts(this);



CurrentLogService.Log("MEF Log Test Pass");

Console.Read();

}

}



注意两个地方

a. 导入声明

        

[Import(typeof(ILogService))]
public ILogService CurrentLogService { get; set; }

 

用接口来定义实例,然后增加导入声明,和导出的相互对应

b. 建立Catalog和Container

var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "TextLog.dll");
var container = new CompositionContainer(catalog);
container.ComposeParts(this);

先这么写,随后再深入挖掘。

6. 把所有项目的输出都指定到同一个目录,也就说让dll和exe在同一目录,运行控制台程序,输出

TextLog: MEF Log Test Pass

 

7.如果我们要输出到数据库,把上面的catalog那一句改成

var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory,"DbLog.dll");

如果不想这么麻烦,这个目录里面只放DbLog.dll 或者TextLog.dll ,然后把上面那句改为:

var catalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory);

 照样可以用。

如果两个都在,还这么搞,那不行的,因为就定义了一个实例,同目录有两个dll。

好了,入门的Demo就到这里。

可以延伸开来,触类旁通,继续深入研究其他概念,例如其他的Catalog\Export等。

原文地址:https://www.cnblogs.com/Leo_wl/p/2361881.html