How does MEF determine the order of its imports?

后端 未结 3 455
野趣味
野趣味 2020-12-28 17:44

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

3条回答
  •  感情败类
    2020-12-28 18:21

    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(
                               lazyRule => lazyRule.Metadata.Order);
        }
    
        [ImportMany]
        public OrderingCollection 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.

提交回复
热议问题