MEF是专门致力于解决扩展性问题的框架,简单的说就是可以动态加载控制
一个特色就是解偶,如A类里有个B类。一般就是在A类的构造函数NEW 一个B
这里用MEF可以解偶出来。
MEF使用最主要的特点就是要配对
[Export(typeof(配对名称))]
public class MemberRepository
[Import(typeof(配对名称))]
public IMemberRepository iMemberRepository { get; set; }
正时生成的iMemberRepository 就是一个实例MemberRepository
生成MEF需要容器初始化
//初始化MEF组合容器
AggregateCatalog catalog = new AggregateCatalog();
//给定的目录(路径,相对路径或绝对路径)中发现导出部件,使用类型DirectoryCatalog
catalog.Catalogs.Add(new DirectoryCatalog(Directory.GetCurrentDirectory()));
//Assembly Catalog(程序集目录)
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
_container = new CompositionContainer(catalog);
try
{
_container.ComposeParts(this);
}
catch (CompositionException compositionException)
{
Console.WriteLine(compositionException.ToString());
}