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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With