[英]How does MEF determine the order of its imports?
MEF允許您通過使用ImportMany
屬性導入多個部件。 它如何確定檢索相關導出的順序並將它們添加到您正在填充的可枚舉中? 例如,如何導入必須以特定順序觸發的多個IRules? 我能想到的唯一方法是在IRule中使用OrderValue屬性並手動排序:
public class Engine
{
[ImportMany]
public IEnumerable<IRule> Rules { get; set; }
public void Run()
{
// ...
// Initialise MEF
// ...
//
// Do I need to manually order Rules here?
//
foreach (IRule rule in Rules)
{
// Must execute in a specific order
rule.Execute();
}
}
}
默認情況下,MEF不保證導入的導出的任何順序。 但是在MEF中,您可以使用一些元數據和自定義集合進行一些排序。 例如,您可以執行以下操作:
public interface IRule { }
[Export(typeof(IRule))]
[ExportMetadata("Order", 1)]
public class Rule1 : IRule { }
[Export(typeof(IRule))]
[ExportMetadata("Order", 2)]
public class Rule2 : IRule { }
public interface IOrderMetadata
{
[DefaultValue(Int32.MaxValue)]
int Order { get; }
}
public class Engine
{
public Engine()
{
Rules = new OrderingCollection<IRule, IOrderMetadata>(
lazyRule => lazyRule.Metadata.Order);
}
[ImportMany]
public OrderingCollection<IRule, IOrderMetadata> Rules { get; set; }
}
然后,您將擁有一組按元數據排序的規則。 您可以在http://codepaste.net/ktdgoh找到OrderingCollection示例。
您可以讓規則按順序相互導入(使用Decorator模式),但是每個規則都需要知道它之前的特定規則,這可能不是您想要的。
MEF可以幫助您發現零件,之后您使用它們取決於您。 如果你想對零件進行分類然后繼續,那就沒有錯!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.