简体   繁体   中英

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

I have an application which exports several objects of the same Class, and plugins which import only specific ones. for example

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

Could someone explain how I can achieve this behavior?

You can name the exports:

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

When you want a specific one,

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

You can still import many of type Part if you don't specify the name.

You need a contract(interface) and a metadata contract (interface):

public interface ICarPart{
    int SomeMethodFromInterface();
}

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

Then you export your parts:

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

Then you can import with ImportMany and 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;
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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