How to prioritize different catalogs in MEF?

一笑奈何 提交于 2020-01-01 05:37:50

问题


I have a AggregateCatalog that contains an AssemblyCatalog and a DirectoryCatalog.

I want them to work like this:

  1. If both catalogs can find an export, choose the one from the DirectoryCatalog.
  2. If neither of them can find an export, then just leave the import to be null.
  3. If only one of them can find an export, then just use that export to fill the import.

How can I achieve something like this?


回答1:


You can achieve point 1. and 3. by putting the catalogs in different export providers, and then passing the export providers to the CompositionContainer constructor in order of priority like this:

var dirCatalog = new DirectoryCatalog(...);
var provider1 = new CatalogExportProvider(dirCatalog);

var assemblyCatalog = new AssemblyCatalog(...);
var provider2 = new CatalogExportProvider(assemblyCatalog);

var container = new CompositionContainer(provider1, provider2);

// link the export providers back to the container, so that they can
// resolve parts from other export providers
provider1.SourceProvider = container;
provider2.SourceProvider = container;

Now you can use the container as usual, and it will look for parts in the directory catalog first, assembly catalog second. You won't get cardinality exceptions when it is present in both.

To achieve point 2., you have to mark individual imports to allow the default value (e.g. null) with [Import(typeof(SomeType),AllowDefault=true].



来源:https://stackoverflow.com/questions/9520170/how-to-prioritize-different-catalogs-in-mef

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!