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.
February 23rd, 2009 at 12:15 pm
This is cool. I was amusing a couple of weeks ago about how I could use something like this.
February 23rd, 2009 at 12:15 pm
Not amusing, musing. :-P
March 27th, 2009 at 11:23 am
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.
March 27th, 2009 at 1:41 pm
whoops, thanks for pointing this out!