How to prioritize different directories in MEF?

I have an AggregateCatalog that contains AssemblyCatalog and DirectoryCatalog.

I want them to work as follows:

  • If both directories can find the export, select one from the DirectoryCatalog directory.
  • If none of them can find the export, just leave it null for it.
  • If only one of them can find the export, simply use this export to fill the import.

How can I achieve something like this?

+4
source share
1 answer

You can reach points 1. and 3. by placing directories in different export providers, and then passing the export providers to the CompositionContainer constructor in priority order as follows:

 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 container , as usual, and first they will look for parts in the catalog directory, and the second - the catalog. You will not receive power exceptions if they are present in both.

To reach point 2., you must mark individual imports so that the default value (for example, null ) is [Import(typeof(SomeType),AllowDefault=true] .

+7
source

Source: https://habr.com/ru/post/1399224/


All Articles