MEF: MSDN 杂志上的文章(13) 重新组合 【暂时用不到,以后再看】
http://msdn.microsoft.com/zh-cn/magazine/ee291628.aspx
允许部件在系统中出现新的匹配导出时自动更新其导入。
[Export]
public class ViewFactory
{
[ImportMany(AllowRecomposition=true)]
IEnumerable<Lazy<IView, IViewMetadata>> Views { get; set; }
public IEnumerable<View>GetViews(ViewTypes viewType) {
return Views.Where(v=>v.Metadata.ViewType.Equals(viewType)).Select(v=>v.Value);
}
}
触发“重新组合”是在“目录 Catalog” 上。
有2个目录会触发重新组合。DirectoryCatalog 和 AggregateCatalog。
- DirectoryCatalog :通过调用其 Refresh 方法来重新组合。
- AggregateCatalog:这是目录的目录。当添加新的目录时,就会重新组合。
void App_Startup(object sender, StartupEventArgs e)
{
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(newDirectoryCatalog((@"\.")));
var container = new CompositionContainer(catalog);
container.Composeparts(this);
base.MainWindow = MainWindow;
this.DownloadAssemblies(catalog);
}
private void DownloadAssemblies(AggregateCatalog catalog)
{
//asynchronously downloads assemblies and calls AddAssemblies
}
private void AddAssemblies(Assembly[] assemblies, AggregateCatalog catalog)
{
var assemblyCatalogs = new AggregateCatalog();
foreach(Assembly assembly in assemblies)
assemblyCatalogs.Catalogs.Add(new AssemblyCatalog(assembly));
catalog.Catalogs.Add(assemblyCatalogs); //这行代码在foreach只外,是为了一次性完成重新组合}
进行重新组合时,集合会立即更新。
结果因集合属性类型而异。
- 如果属性类型是 IEnumerable<T>,则它将替换为新实例。
- 如果它是继承自 List<T> 或 ICollection 的具体集合,则 MEF 将对每一项依次调用 Clear 和 Add。
无论是哪一种情况,都意味着在使用重新组合时必须考虑线程安全。
重新组合不仅与添加有关,也与删除有关。如果从容器中移除目录,则也会移除这些部件。
浙公网安备 33010602011771号