Search code examples
c#mef

MEF throws exception ImportCardinalityMismatchException?


What is a possible reason for MEF throwing an ImportCardinalityMismatchException?


Solution

  • The code below demonstrates how to reproduce this error.

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

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

    The problem is that MEF wants to construct a Person object, but it cant finish 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; }
        }
    }