Geeks With Blogs
Sean's Blog My Development Blog

I attended MIX11 a couple of weeks ago and had the opportunity to meet up with Glen Block at one of the open source festival booths where he was demoing MEF (Managed Extensibility Framework). During his demonstration, he showed a very cool (in my opinion) feature of MEF that allows you to export a concrete class that may or may not implement some predefined interface. This is done through the magic of the C# 4.0 dynamic keyword, which allows the compiler to bypass static type checking during compilation.

Take the following code as an example:

[Export("Message")] public class MessagePart { public MessagePart() { Message = "I can haz dynamic"; } public string Message { get; set; } }

Notice the above code does not implement any particular interface. How would we import it and pass it as a parameter to, for example, another classes constructor? As previously mentioned, through the magic of the C# 4.0 dynamic feature

[Export] public class MainViewModel { [ImportingConstructor] public MainViewModel([Import("Message")] dynamic messagePart) { Message = messagePart.Message; } public string Message { get; set; } }

And that’s it! Notice the messagePart parameter is dynamic. MEF still imports the concrete type that exports the contract (in this case with the name Message). As with all dynamic types in C#, the static type checking is done at runtime.

Posted on Tuesday, April 26, 2011 1:30 PM | Back to top

Comments on this post: Dynamic Exports with MEF

No comments posted yet.
Your comment:
 (will show your gravatar)

Copyright © Sean Fao | Powered by: