简 介
MEF的关键概念
它是如何工作的?
用 MEF 实现一个最简单的可扩展应用程序
1
2
3
4
5
6
|
public
interface
IPlugin
{
string
Text {
get
; }
void
Do();
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public
partial
class
Form1 : Form
{
public
Form1()
{
InitializeComponent();
}
[ImportMany]
public
IEnumerable<IPlugin> plugins;
private
void
Form1_Load(
object
sender, EventArgs e)
{
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
[Export(
typeof
(IPlugin))]
public
class
MyPlugin:IPlugin
{
public
string
Text
{
get
{
return
"This is a demo"
;
}
}
public
void
Do()
{
MessageBox.Show(Text);
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
private
CompositionContainer _container;
private
void
Init()
{
try
{
MyPlugin my =
new
MyPlugin();
this
._container.ComposeParts(
this
, my);
//把扩展和实例组合在一起
}
catch
(CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
private
CompositionContainer _container;
private
void
Init()
{
//设置目录,让引擎能自动去发现新的扩展
var
catalog =
new
AggregateCatalog();
catalog.Catalogs.Add(
new
DirectoryCatalog(
"D:\\plugin\\"
));
//创建一个容器,相当于是生产车间
_container =
new
CompositionContainer(catalog);
//调用车间的ComposeParts把各个部件组合到一起
try
{
this
._container.ComposeParts(
this
);
//这里只需要传入当前应用程序实例就可以了,其它部分会自动发现并组装
}
catch
(CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}
}
|
1
2
3
4
|
foreach
(
string
di
in
Directory.EnumerateDirectories(
"D:\\plugin\\"
))
{
catalog.Catalogs.Add(
new
DirectoryCatalog(di));
}
|
1
2
|
catalog.Catalogs.Add(
new
DirectoryCatalog(
"D:\\plugin\\"
));
//加载 dll
catalog.Catalogs.Add(
new
DirectoryCatalog(
"D:\\plugin\\"
,*.exe));
//加载 exe
|