[英]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.