MEF抛出异常ImportCardinalityMismatchException?

时间:2013-09-19 09:14:22

标签: c# mef

MEF抛出ImportCardinalityMismatchException的可能原因是什么?

1 个答案:

答案 0 :(得分:4)

下面的代码演示了如何重现此错误。

要进行测试,请确保使用.NET 4.5进行编译,然后添加MEF程序集:

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

问题在于MEF想要构造一个Person对象,但是它无法完成它的属性注入" Age" (标记为"导入")。

要重现错误,请注释掉下面标记的行。

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; }
    }
}