2012-01-26 5 views
4

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

답변

9

ImportingConstructor 속성에만 작동합니다. Prim(int val) 생성자는 MEF가 생성자에 대해 제공 할 값을 알지 못하므로 합성에 실패합니다.

이 시나리오는 MEF 팩토리 패턴에 훨씬 적합한 것처럼 보입니다.

interface IPrimitiveDecomposerFactory { 
    IPrimitiveDecomposer Create(int value); 
} 

[Export(typeof(IPrimitiveDecomposerFactory))] 
sealed class PrimitiveDecomposerFactor : IPrimitiveDecomposerFactory { 
    public IPrimitiveDecomposer Create(int value) { 
    return new Prim(value); 
    } 
} 

이제 코드는 IPrimitiveDecomposerFactory를 가져올 특정 int

을 기반으로 IPrimitiveDecomposer 인스턴스를 생성하는 데 사용할 수 있습니다
관련 문제