Catching MEF Error: ImportCardinalityMismatchException

Aug 5, 2011 at 5:49 PM

If this is possible, or reasonable, I'm guessing (hoping) it's easy.

So here's the question upfront: is there a way in code to catch this exception?  Basically, I want to cause a hard break (so other developers don't waste the time I wasted) and give the troubleshooting tips.

 

Here's why I want to do it:

In XAML, I was using a locator to find MyVewModel. In code, I was exporting MyViewModel.  (You'll notice I was missing an i)

As a result, I was getting an error in the Output window of:

Error while resolving ViewModel. System.ComponentModel.Composition.ImportCardinalityMismatchException: No valid exports were found that match the constraint '((((exportDefinition.ContractName == "MyViewModel") AndAlso (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") AndAlso "System.Object".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity")))) AndAlso (((exportDefinition.Metadata.ContainsKey("Name") AndAlso System.String.IsInstanceOfType(exportDefinition.Metadata.get_Item("Name"))) AndAlso exportDefinition.Metadata.ContainsKey("IsViewModelFirst")) AndAlso System.Boolean.IsInstanceOfType(exportDefinition.Metadata.get_Item("IsViewModelFirst")))) AndAlso ((Not(exportDefinition.Metadata.ContainsKey("System.ComponentModel.Composition.CreationPolicy")) OrElse Any.Equals(exportDefinition.Metadata.get_Item("System.ComponentModel.Composition.CreationPolicy"))) OrElse NonShared.Equals(exportDefinition.Metadata.get_Item("System.ComponentModel.Composition.CreationPolicy"))))', invalid exports may have been rejected.
   at System.ComponentModel.Composition.Hosting.ExportProvider.GetExports(ImportDefinition definition, AtomicComposition atomicComposition)

Eventually, I realized this was being written to the Output Window (at first, I was simply getting no results and had to backtrack it in code with breakpoints).  Even then, it took me quite a while to find it. 

 

So here's the question again: is there a way in code to catch this exception?  Basically, I want to cause a hard break (so other developers don't waste the time I wasted) and give the troubleshooting tips.

Sep 6, 2011 at 11:05 PM

You can't catch the ImportCardinalityException directly as - by the look of things - it gets thrown as a part of the import satisfaction process; which then gets picked up by the rejection mechanics, and the part gets discarded. Tracing is your only option to achieve any sort of a "hard break".

That said in .Net 4.5 (and the latest bits published on CodePlex), we have an option to turn off rejection altogether, which will result in an exception getting thrown (naturally this would mean no rejection will take place and your composition will be in an indeterminate state).

Hope this helps

Oleg