MEF throws ImportCardinalityMismatchException?

What is the possible reason that MEF throws an ImportCardinalityMismatchException?

+4
source share
1 answer

The code below shows how to reproduce this error.

To test, make sure you are compiling with .NET 4.5 and add the MEF assemblies:

  • System.ComponentModel.Composition
  • System.ComponentModel.Composition.Registration

The problem is that MEF wants to build a Person object, but it cannot complete its property injection for "Age" (which is marked as "Import").

To reproduce the error, comment out the line marked below.

using System; using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; using System.Reflection; namespace ForStackOverflow { public class Program { public static void Main(string[] args) { var container = new CompositionContainer( new AssemblyCatalog(Assembly.GetExecutingAssembly())); // Comment out this next line to get an // ImportCardinalityMismatchException error container.ComposeExportedValue("Age", 30); var person = container.GetExportedValue<Person>(); Console.WriteLine("Persons age: " + person.Age); Console.WriteLine("[press any key to continue]"); Console.ReadKey(); } } [Export] public class Person { [ImportingConstructor] public Person() { } [Import("Age")] public int Age { get; set; } } } 
+4
source

All Articles