五 基于约定的部件注册
.NET4.5以后MEF增添了新功能,该功能就是基于约定的部件注册,它不再需要导出的部件使用特性(export)。用处:第一,不能访问类的源代码,而该类需要作部件,此时该类需要添加导出特性,使用该功能可避免此问题;第二,用户不希望处理入口的特性。
基于约定的部件注册需要添加引用System.ComponentModel.Composition.Registration
下面基于IUserInfo例子来讲解,将插件程序集中export那一行语句删除,宿主应用程序的Import删除。
宿主应用程序变更比较大,代码如下:
using System;
using System.ComponentModel.Composition;
using Plug;
using System.ComponentModel.Composition.Hosting;
namespace MEFTest1
{
classProgram
{
// [Import]
publicIUserInfo userInfo { get; set; }
staticvoid Main(string[] args)
{
var p = newProgram();
p.Run();
}
publicvoid Run()
{
var conventions = new RegistrationBuilder();
conventions.ForTypesDerivedFrom<IUserInfo>().Export<IUserInfo>();
conventions.ForType<Program>().ImportProperty<IUserInfo>(p=> p.userInfo);
varcatalog = new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, conventions);
using(CompositionService service = catalog.CreateCompositionService())
{
service.SatisfyImportsOnce(this, conventions);
}
//var catalog = newDirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory);
//var container =new CompositionContainer(catalog);
//try
//{
// container.ComposeParts(this);
//}
//catch(ChangeRejectedException ex)
//{
// Console.WriteLine(ex.Message);
// return;
//}
string info =userInfo.showUserInfo("luna","12345678");
Console.WriteLine(info);
Console.ReadKey();
}
}
}
红色代码是基于约定的部件注册的核心,具体使用的是RegistrationBuilder,这里对此不作具体介绍。
MEF基础部分暂告一段落,后期如果编写MEF框架,会分享一些深入地东西。