5

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?

Cui Pengfei 崔鹏飞
  • 8,017
  • 6
  • 46
  • 87
  • 1
    Have a look at [Replacing components with MEF](http://greenicicleblog.com/2010/07/19/replacing-components-with-mef/) They discuss how you could alter MEF so that you can prioritize exports – Terkel Mar 01 '12 at 16:42
  • @Simon Bang Terkildsen thanks, i have seen this blog. but it requires a customized catalog and attribute, while i am looking for a simpler way. – Cui Pengfei 崔鹏飞 Mar 01 '12 at 16:48

1 Answers1

8

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].

Wim Coenen
  • 66,094
  • 13
  • 157
  • 251
  • 1
    by the way, is this documented? – Cui Pengfei 崔鹏飞 Mar 02 '12 at 21:02
  • 1
    @CuiPengFei: I'm not sure where I picked this up. Perhaps by reading [Glenn Block's blog](http://blogs.msdn.com/b/gblock/archive/2009/05/14/customizing-container-behavior-part-2-of-n-defaults.aspx) (former MEF product manager) or in the [samples at codeplex](http://mef.codeplex.com/wikipage?title=Samples&referringTitle=Documentation) – Wim Coenen Mar 02 '12 at 22:28