MEF 용 IPrimitiveDecomposer 인터페이스를 구현하고 Node 기본 클래스를 상속하는 Prim 클래스가 있습니다. 나는 매개 변수가없는 생성자가없는 클래스를 상속 할 때C#/MEF는 매개 변수없는 생성자가없는 기본 클래스에서 작동하지 않습니다.
public class Node
{
public Node()
{
}
}
public interface IPrimitiveDecomposer
{
bool Match(Node node);
}
[Export(typeof(IPrimitiveDecomposer))]
public class Prim : Node, IPrimitiveDecomposer
{
public bool Match(Node node) {return true;}
}
그러나, MEF의 ComposeParts() 메소드는 프림 개체를 가져올 수 없습니다. 속성없이 컴파일 오류가 발생하여 this page in MSDN 다음에 ImportingConstructor 특성을 추가했습니다.
[Export(typeof(IPrimitiveDecomposer))]
public class Prim : Node, IPrimitiveDecomposer
{
[ImportingConstructor]
public Prim(int val) : base (val)
{}
public bool Match(Node node) {return true;}
}
작동하지 않는 코드는 다음과 같습니다. Node 클래스에 대해 매개 변수없는 생성자를 제공하면 작동합니다. 생성자에 매개 변수가 MEF 개체를 내보낼 때
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Reflection;
public class Node
{
public Node(int val)
{
}
}
public interface IPrimitiveDecomposer
{
bool Match(Node node);
}
[Export(typeof(IPrimitiveDecomposer))]
public class Prim : Node, IPrimitiveDecomposer
{
[ImportingConstructor]
public Prim(int val) : base (val)
{}
public bool Match(Node node) {return true;}
}
public class Test
{
[ImportMany(typeof(IPrimitiveDecomposer), AllowRecomposition = true)]
private IEnumerable<IPrimitiveDecomposer> PrimitiveDecomposers { get; set; }
void mef()
{
// MEF
var catalog = new AggregateCatalog();
catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
static void Main()
{
var mef = new Test();
mef.mef();
var res = mef.PrimitiveDecomposers;
foreach(var it in res)
{
Console.WriteLine(it);
}
}
}