如何MEF确定其进口秩序? [英] How does MEF determine the order of its imports?

查看:144
本文介绍了如何MEF确定其进口秩序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MEF使您可以通过使用 ImportMany 属性导入多个部分。它是如何确定它检索相关的出口,并将它们添加到您的填充枚举的顺序?例如,我将如何导入多个的iRules是有一个特定的顺序火?我能想到的唯一的办法就是在iRule中和手动排序的OrderValue属性:

 公共类发动机
{
[ImportMany]
公开的IEnumerable<&的iRule GT;规则{搞定;组; }

公共无效的run()
{
// ...
//初始化MEF
// ...

//
//我需要在这里手动规程规定?
//

的foreach(在规则的iRule规则)
{
//必须按照特定的顺序
rule.Execute的execute();
}
}
}


解决方案

默认情况下MEF并不能保证获得进口出口的任何命令。然而,在MEF可以使用一些元数据和一个自定义集合做一些订货。例如,你可以这样做:

 公共接口的iRule {} 

[导出(typeof运算(的iRule))]
[ExportMetadata(订单,1)]
公共类规则1:的iRule {}

[导出(typeof运算(的iRule))]
[ExportMetadata(订单,2)]
类公共规则2:的iRule {}

公共接口IOrderMetadata
{
[默认值(Int32.MaxValue)]
INT订单{搞定; }
}

公共类发动机
{
公共引擎()
{
规则=新OrderingCollection<的iRule,IOrderMetadata>(
lazyRule => lazyRule.Metadata.Order);
}

[ImportMany]
公共OrderingCollection<的iRule,IOrderMetadata>规则{搞定;组; }
}



然后,你将有一组由元数据排序的规则。您可以在 http://codepaste.net/ktdgoh 的OrderingCollection样本。


MEF allows you to import multiple parts via the use of the ImportMany attribute. How does it determine the order in which it retrieves the relevant exports and adds them to the enumerable you are populating? For example, how would I import multiple IRules that had to fire in a particular order? The only way I can think of is to have an OrderValue property in IRule and sort manually:

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

解决方案

By default MEF does not guarantee any order of the exports that get imported. However in MEF you can do some ordering by using some metadata and a custom collection. For example you can do something like:

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

Then you will have a set of rules that are ordered by the metadata. You can find the OrderingCollection sample at http://codepaste.net/ktdgoh.

这篇关于如何MEF确定其进口秩序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆