C#MEF:导出一种类型的多个对象,并导入特定的对象

时间:2011-11-02 13:53:36

标签: c# wpf import export mef

我有一个应用程序,它导出同一个Class的几个对象,以及只导入特定类的插件。例如

public class Part
{
  string name;
  public Part(string nm)
  {
    name = nm;
  }
}

public class Car //Exports ALL Parts of the Car
{
  [Export(typeof(Part))]
  public Part steeringWheel = new Part("SteeringWheel");

  [Export(typeof(Part))]
  public Part engine = new Part("Engine");

  [Export(typeof(Part))]
  public Part brakes = new Part("Brakes");
}

public class SystemMonitorPlugin //Imports only SOME Parts from the Car
{
  [Import(typeof(Part))]
 public Part engine;

  [Import(typeof(Part))]
  public Part brakes;
}

有人可以解释我是如何实现这种行为的吗?

2 个答案:

答案 0 :(得分:10)

您可以为导出命名:

[Export("SteeringWheel", typeof(Part))]

如果你想要一个特定的,

[Import("Engine", typeof(Part))]

如果您未指定名称,仍可以导入许多类型的部分。

答案 1 :(得分:4)

您需要合同(接口)和元数据合同(接口):

public interface ICarPart{
    int SomeMethodFromInterface();
}

public interface ICarPartMetadata{
    string /*attention to this!!!*/ NameCarPart { get; } /* Only for read. */
}

然后导出您的部件:

[Export(typeof (ICarPart))]
[ExportMetadata("NameCarPart","SteeringWheel")] /* is string!! */

public class SteeringWheel : ICarPart {

    public int SomeMethodFromInterface(){
        ... //your stuff
    }
}
[Export(typeof (ICarPart))]
[ExportMetadata("NameCarPart","Engine")] /* is string!! */

public class Engine : ICarPart {

    public int SomeMethodFromInterface(){
        //Each method have diferent behavior in each part.
        ... //your stuff
    }
}
[Export(typeof (ICarPart))]
[ExportMetadata("NameCarPart","Brakes")] /* is string!! */

public class Brakes : ICarPart {

    public int SomeMethodFromInterface(){
        //Each method have diferent behavior in each part.
        ... //your stuff
    }
}

然后您可以使用ImportMany和Lazy导入:

    [ImportMany()]
    IEnumerable<Lazy<ICarPart, ICarPartMetadata>> carParts = null;
    public void Importing(){
    ...
    ...

    foreach (Lazy<ICarPart,ICarPartMetadata> item in carParts){
        switch (item.Metadata.ICarPartMetadata.ToString()){
            case "SteeringWheel":
                item.Value.SomeMethodFromInterface();
            break;
            case "Engine":
                item.Value.SomeMethodFromInterface();
            break;
            case "Brakes":
                item.Value.SomeMethodFromInterface();
            break;
            default:
            ...
            break;
        }
    }