Imports identified via custom attributes

Jun 1, 2010 at 12:25 AM

I need to import a collection of delgates that are identified via a custom attribute? i.e., for every method that has [NavigationRule("X","Y","Z")] defined I need to add to a list of delegates. To make it a little more complicated I need to be able to locate the method in the delegate collection based on the X,Y,Z.

Developer
Jun 4, 2010 at 5:37 PM

For this to work you would need to write a custom ExportAttribute by making NavigationRuleAttribute inherit from ExportAttribute then you can define "X", "Y', "Z" as properties on that attribute which would make them metadata values on the export.  Here is a code snippet that I think will get you close:

public interface INavigationRuleMetadata
{
    string X { get; }
    string Y { get; }
    string Z { get; }
}
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class NavigationRuleAttribute : ExportAttribute, INavigationRuleMetadata
{
    public NavigationRuleAttribute(string x, string y, string z)
        : base("NavigationRule", typeof(Action<object>))
    {
        this.X = x;
        this.Y = y;
        this.Z = z;
    }

    public string X { get; set; }
    public string Y { get; set; }
    public string Z { get; set; }
}

public class Foo
{
    [ImportMany("NavigationRule", typeof(Action<object>))]
    public IEnumerable<Lazy<Action<object>, INavigationRuleMetadata>> NavigationRules { get; set; }

    public void ExecuteRules(string x, object obj)
    {
        foreach (var rule in NavigationRules.Where(rule => rule.Metadata.X == x))
        {
            rule.Value.Invoke(obj);
        }
    }
}