繁体   English   中英

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

[英]C# MEF: Exporting multiple objects of one type, and Importing specific ones

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

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

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

您可以命名导出:

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

当你想要一个特定的,

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

如果未指定名称,仍可以导入许多类型的零件。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM