簡體   English   中英

MEF如何確定其進口的順序?

[英]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示例。

在MEF中實現此排序的最佳方式是利用我們的元數據設施。 您可以將自己的元數據附加到可用於排序和過濾的導出。 元數據還允許您延遲部件的實例化,直到實際需要它們為止。 此外,您可以創建自定義導出屬性,這些屬性提供了一種提供元數據的簡潔方法。

有關如何定義元數據和自定義導出的信息,請查看此鏈接: 鏈接文本

您也可以在我們的MEF論壇上找到這個主題。 在其中您將找到有關AdaptingCollection方法的討論,該方法允許您使用應用元數據過濾器/訂單的自定義集合。

HTH Glenn

您可以讓規則按順序相互導入(使用Decorator模式),但是每個規則都需要知道它之前的特定規則,這可能不是您想要的。

MEF可以幫助您發現零件,之后您使用它們取決於您。 如果你想對零件進行分類然后繼續,那就沒有錯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM