Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MEF throws exception ImportCardinalityMismatchException?

Tags:

c#

mef

What is a possible reason for MEF throwing an ImportCardinalityMismatchException?

like image 751
Contango Avatar asked Sep 19 '13 09:09

Contango


1 Answers

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; }
    }
}
like image 89
Contango Avatar answered Nov 08 '22 03:11

Contango