MEF: Exporting and importing methods

February 17th, 2009

This is an interesting feature of MEF, usually overseen (maybe because it’s not documented anywhere). You can export methods with a specific shape and import them to delegates:

public class Validation
{
    [Export("validator")]
    public bool ValidateEmail(string value)
    {
        return true;
    }

    [Export("validator")]
    public bool ValidateNonEmpty(string value)
    {
        return true;
    }
}

[Export]
public class FormToValidate
{
    [Import("validator")]
    public IEnumerable<Func<string, bool>> Validators { get; set; }

    public void ValidateName(string username)
    {
        foreach(var validator in Validators)
        {
            if (!validator(username))
            {
                throw new Exception("validation error");
            }
        }
    }
}

Before you ask, yes this feature came from real world scenarios and we have plenty of customers using it. So far, we are constrained by the maximum number of arguments Func/Action supports, but Wes is in the process of fixing that.

Categories: MEF | Top Of Page | 4 Comments » |

4 Responses to “MEF: Exporting and importing methods”

Christopher Bennage Says:

This is cool. I was amusing a couple of weeks ago about how I could use something like this.

Christopher Bennage Says:

Not amusing, musing. :-P

Rafael Teixeira Says:

Snippet shows:

[Import("validator")]
public IEnumerable> Validators { get; set; }

I thought the generic parameter for the IEnumerable got swallowed in the publishing, and sure, viewing the HTML source it is there

<Func<string, bool>>

:( – Publishing (C++,C#,Java) generics code in blogs is really a bothersome endeavor currently.

hammett Says:

whoops, thanks for pointing this out!

Leave a Reply