<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/atom.xsl" media="screen"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en-US"><title type="html">Daniel Plaisted&amp;#39;s Blog</title><subtitle type="html" /><id>http://blogs.msdn.com/b/dsplaisted/atom.aspx</id><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/" /><link rel="self" type="application/atom+xml" href="http://blogs.msdn.com/b/dsplaisted/atom.aspx" /><generator uri="http://telligent.com" version="5.6.50428.7875">Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><updated>2008-11-13T21:56:59Z</updated><entry><title>Caller Info Attributes in Portable Class Libraries</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2012/09/18/caller-info-attributes-in-portable-class-libraries.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2012/09/18/caller-info-attributes-in-portable-class-libraries.aspx</id><published>2012-09-18T14:30:02Z</published><updated>2012-09-18T14:30:02Z</updated><content type="html">&lt;p&gt;With the release of .NET 4.5 and Visual Studio 2012, C# and Visual Basic support &lt;a href="http://msdn.microsoft.com/en-us/library/hh534540.aspx"&gt;Caller Info attributes&lt;/a&gt; which provide a simple way to get information about the caller of a method.&amp;#160; This can be useful for tracing and diagnostic methods and can also make it easier to implement INotifyPropertyChanged.&amp;#160; For example, you can use a helper method like the following to raise property changed notifications:&lt;/p&gt;  &lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;protected bool SetProperty&amp;lt;T&amp;gt;(ref T storage, T value,
                             [CallerMemberName] string propertyName = null)
{
    if (object.Equals(storage, value)) return false;

    storage = value;
    this.OnPropertyChanged(propertyName);
    return true;
}&lt;/pre&gt;

&lt;p&gt;Then you can write simple properties like this:&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;string _title;
public string Title
{
    get { return _title; }
    set { SetProperty(ref _title, value); }
}&lt;/pre&gt;

&lt;p&gt;This way you don’t have to explicitly specify the name of the property that changed, which means it won’t accidentally get out of sync if you change the property name.&amp;#160; (As a side note, in my opinion this is still more verbose than it should be.&amp;#160; You can use &lt;a href="https://github.com/SimonCropp/NotifyPropertyWeaver"&gt;NotifyPropertyWeaver&lt;/a&gt; or &lt;a href="http://nuget.org/packages/PropertyChanged.Fody"&gt;PropertyChanged.Fody&lt;/a&gt; to add property change notification code automatically as a post-compile step.)&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h2&gt;Caller Info in Portable Class Libraries&lt;/h2&gt;

&lt;p&gt;The caller info attributes are part of .NET 4.5, .NET for Windows Store apps, and Windows Phone 8.&amp;#160; If you create a portable library restricted to those targets, you will be able to use the caller info attributes.&amp;#160; If you need to target a platform that doesn’t include these attributes, such as .NET 4, Windows Phone 7, or Silverlight, they won’t be available.&lt;/p&gt;

&lt;p&gt;However, the caller info functionality is strictly a function of the compiler, and the compiler doesn’t care where those attributes are defined.&amp;#160; So if you are using the new compiler but targeting an earlier platform, you can &lt;a title="Using C# 5 caller info attributes when targeting earlier versions of the .NET framework" href="http://www.thomaslevesque.com/2012/06/13/using-c-5-caller-info-attributes-when-targeting-earlier-versions-of-the-net-framework/"&gt;define the attributes yourself&lt;/a&gt; and get the caller info functionality.&amp;#160; This technique will also work for portable libraries targeting platforms that don’t include these attributes.&amp;#160; So basically, you just need to include the following code in your portable library and you can use caller info attributes on pretty much any platform or portable library.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;namespace System.Runtime.CompilerServices
{
    // Summary:
    //     Allows you to obtain the method or property name of the caller to the method.
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    sealed class CallerMemberNameAttribute : Attribute { }

    // Summary:
    //     Allows you to obtain the line number in the source file at which the method
    //     is called.
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public sealed class CallerLineNumberAttribute : Attribute { }

    // Summary:
    //     Allows you to obtain the full path of the source file that contains the caller.
    //     This is the file path at the time of compile.
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public sealed class CallerFilePathAttribute : Attribute { }
}&lt;/pre&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10350492" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>How to Make Portable Class Libraries Work for You</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2012/08/27/how-to-make-portable-class-libraries-work-for-you.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2012/08/27/how-to-make-portable-class-libraries-work-for-you.aspx</id><published>2012-08-27T16:06:00Z</published><updated>2012-08-27T16:06:00Z</updated><content type="html">&lt;p&gt;A &lt;a href="http://msdn.microsoft.com/en-us/library/gg597391(v=vs.110).aspx"&gt;Portable Class Library&lt;/a&gt; is a .NET library that can be used (in binary form, without recompiling) on multiple .NET platforms.&amp;#160; When you create a Portable Class Library in Visual Studio, you can choose which platforms to target.&amp;#160; Portable libraries support targeting the .NET Framework, Silverlight, Windows Phone, Windows Store apps, and XBox 360 XNA games.&lt;/p&gt;  &lt;table style="width: 100%" border="0" cellspacing="0" cellpadding="2"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" align="center"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Portable Class Library Creation Dialog in Visual Studio 2012" border="0" alt="Portable Class Library dialog to choose target frameworks" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/2477.Portable_2D00_Class_2D00_Library_2D00_Creation_2D00_Dialog_2D00_VS2012_5F00_7922EAF8.png" width="385" height="375" /&gt;&amp;#160;&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" align="center"&gt;&lt;em&gt;Portable Class Library creation dialog in Visual Studio 2012&lt;/em&gt;&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;   &lt;br clear="all" /&gt;This can be a big improvement over creating a separate project file for each platform you want to target, and keeping them all in sync.&amp;#160; For example, shown below is the project structure for the &lt;a href="http://mvvmlight.codeplex.com/"&gt;MVVM Light Toolkit&lt;/a&gt;.&lt;/p&gt;  &lt;table style="width: 100%" border="0" cellspacing="0" cellpadding="2"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="100%" align="center"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="MVVM Light Toolkit Project Structure" border="0" alt="MVVM Light Toolkit Project Structure" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/1321.MVVMLightProjectsCropped_5F00_5EC54457.png" width="238" height="310" /&gt;&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="100%" align="center"&gt;&lt;em&gt;MVVM Light Toolkit Project Structure&lt;/em&gt;&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;   &lt;br clear="all" /&gt;I bet it’s not fun to keep all those projects in sync each time a file needs to be added, removed, or renamed.&amp;#160; There are only three logical libraries here (the core library, extras, and the tests).&amp;#160; Wouldn’t it be great to just have one portable version of each of those libraries instead of seven different ones?&lt;/p&gt;  &lt;h1&gt;Trouble in Paradise&lt;/h1&gt;  &lt;p&gt;Unfortunately, it’s not that simple.&amp;#160; The fact that Portable Class Libraries need to run on multiple platforms imposes some constraints on what you can do in them.&amp;#160; Many .NET Framework APIs (such as File I/O or anything to do with the user interface) aren’t available.&amp;#160; Portable libraries can’t reference non-portable libraries.&amp;#160; You can’t use P/Invoke from most portable libraries.&amp;#160; This is all because portable libraries are supposed to actually run on different platforms, but it means it can be more complicated to write them, and can in some cases be very difficult (or not possible) to convert existing .NET libraries to portable libraries.&lt;/p&gt;  &lt;p&gt;We’ve seen lots of people excited about portable libraries, but we’ve also seen some people who have run into these limitations questioning whether portable libraries are useful for them.&amp;#160; In this post, I’ll cover how you can use Portable Class Libraries even when you run into these limitations.&amp;#160; First, let’s look at the reasons some APIs aren’t supported, and what functionality actually is supported.&lt;/p&gt;  &lt;h1&gt;&lt;/h1&gt;  &lt;h1&gt;Why APIs Aren’t Portable&lt;/h1&gt;  &lt;p&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="API Y U NO PORTABLE" border="0" alt="API Y U NO PORTABLE" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/2475.API_2D00_Y_2D00_U_2D00_NO_2D00_PORTABLE_5F00_11B28849.jpg" width="400" height="300" /&gt;&lt;/p&gt;  &lt;p&gt;Here are some of the reasons APIs aren’t available in portable libraries (taken from &lt;a href="https://twitter.com/davkean"&gt;David Kean&lt;/a&gt;’s MSDN article on &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh852593.aspx"&gt;Creating a Continuous Client Using Portable Class Libraries&lt;/a&gt;):&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The API Isn’t Implemented by All Platforms      &lt;br /&gt;&lt;/strong&gt;Traditional .NET Framework file IOs, such as System.IO.File and System.IO.Directory, fall into this bucket. Silverlight and Windows Phone use the System.IO.IsolatedStorage APIs (though different from the .NET Framework version), whereas Windows Store apps use Windows.Storage.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The API Isn’t Compatible Across All Platforms      &lt;br /&gt;&lt;/strong&gt;Some APIs look and feel the same, but it’s hard or impossible to write code against them in a portable and consistent way. ThreadStaticAttribute, which enables static fields to have a unique value for each thread, is an example. Though it’s present on both the Windows Phone and Xbox platforms, neither of their runtimes supports it.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;The API Is Considered Obsolete or Legacy&lt;/strong&gt;     &lt;br /&gt;These APIs either contain behavior that’s unlikely to be present on future platforms, or they’ve been replaced by newer technologies. BackgroundWorker is an example of this; it was replaced by Task and the new asynchronous program features in Visual Studio 2012.&lt;/p&gt;  &lt;p&gt;&lt;strong&gt;We Ran out of Time&lt;/strong&gt;     &lt;br /&gt;Most APIs weren’t written with portability in mind. We spend a significant amount of time going through each API to make sure it can be programmed against in a portable manner. This might involve tweaking or adding to the API to make it portable. Because of the time and effort involved, in the first version of PCLs we made available on Visual Studio Gallery, we prioritized the high-value, highly used APIs. System.Xml.Linq.dll and System.ComponentModel.DataAnnotations.dll are examples of APIs that weren’t available in that first version but are now available in the Visual Studio 2012 release.&lt;/p&gt;  &lt;h1&gt;What Is Supported in Portable Libraries?&lt;/h1&gt;  &lt;p&gt;For a .NET Framework API to be available in a portable library, the API needs to be supported on all the platforms the portable library is targeting.&amp;#160; This means that the platforms you choose to target in your portable library affect the APIs that are available to you.&amp;#160; In general, the more platforms you choose to support, the fewer APIs will be available to you.&amp;#160; For example, the Task type from the TPL is available in .NET 4 and up, Silverlight 5, and Windows Store apps.&amp;#160; So if you target only those platforms you will be able to use the Task type in your portable library.&amp;#160; If you target Silverlight 4, XBox, or Windows Phone 7, you won’t be able to use it.&lt;/p&gt;  &lt;p&gt;The following chart gives a summary of what API areas are available in portable libraries and on what platforms.&lt;/p&gt;  &lt;table style="width: 100%" border="0" cellspacing="0" cellpadding="2"&gt;&lt;tbody&gt;     &lt;tr&gt;       &lt;td valign="top" width="100%" align="center"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Portable Class Library Platform and Feature Matrix" border="0" alt="Portable Class Library Platform and Feature Matrix" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/1715.Portable_2D00_Class_2D00_Library_2D00_Platform_2D00_and_2D00_Feature_2D00_Matrix_5F00_3FFE7A7A.png" width="570" height="417" /&gt;&lt;/td&gt;     &lt;/tr&gt;      &lt;tr&gt;       &lt;td valign="top" width="100%" align="center"&gt;&lt;em&gt;Portable Class Library Platform/Feature Support Matrix&lt;/em&gt;&lt;/td&gt;     &lt;/tr&gt;   &lt;/tbody&gt;&lt;/table&gt;  &lt;p&gt;   &lt;br clear="all" /&gt;The full list of APIs available in portable libraries as of Visual Studio 2012 RTM is available in this spreadsheet: &lt;a href="http://sdrv.ms/OVdfNc"&gt;Portable Class Library APIs&lt;/a&gt;&lt;/p&gt;  &lt;h1&gt;Solving Problems With Indirection&lt;/h1&gt;  &lt;blockquote&gt;   &lt;p&gt;&lt;em&gt;Any problem in computer science can be solved with another layer of indirection.&lt;/em&gt; – David Wheeler (&lt;a href="http://stackoverflow.com/questions/2057503/does-anybody-know-from-where-the-layer-of-abstraction-layer-of-indirection-q"&gt;probably&lt;/a&gt;)&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;What should you do when you’re trying to write a portable library but you need some functionality that isn’t supported?&amp;#160; You can’t call the API directly, and you can’t reference a library that does, because portable libraries can’t reference non-portable libraries.&amp;#160; The solution is to create an abstraction in your portable library that provides the functionality you need, and to implement that abstraction for each platform your portable library targets.&amp;#160; For example, if you need to save and load text files, you might use an interface like this:&lt;/p&gt;  &lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public interface IFileStorage
{
    Task SaveFileAsync(string filename, string contents);
    Task&amp;lt;String&amp;gt; LoadFileAsync(string filename);
}&lt;/pre&gt;

&lt;p&gt;It’s a good idea to include only the functionality you need in the abstraction.&amp;#160; In this example, the interface doesn’t abstract general file system concepts such as streams, folders, or enumerating files.&amp;#160; This makes the abstraction more portable and easier to implement.&amp;#160; The methods return Tasks so that the implementation for Windows Store apps can call the WinRT file IO APIs, which are async.&lt;/p&gt;

&lt;p&gt;Creating an abstraction allows portable libraries to call into non-portable code, and this pattern is applicable almost any time you need to access non-portable functionality from a portable library.&amp;#160; Of course, you need some way for the portable code to get a reference to an implementation of the abstraction.&amp;#160; How you do that can depend on whether you are writing a cross platform app or a general purpose reusable library.&lt;/p&gt;

&lt;h1&gt;Cross Platform Apps&lt;/h1&gt;

&lt;p&gt;When writing a cross platform app in .NET, you should create the user interface separately for each platform to take advantage of the screen sizes and UI metaphors of each platform.&amp;#160; To avoid duplicating work, you’d like most of the rest of your code to be shared across platforms.&amp;#160; A clean separation between your user interface and the rest of your code will make this easier, and a great pattern for this is the &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;Model-View-View Model (MVVM) pattern&lt;/a&gt;.&lt;/p&gt;

&lt;table style="width: 100%" border="0" cellspacing="0" cellpadding="2"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td valign="top" width="100%" align="center"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Diagram of the MVVM Pattern" border="0" alt="Diagram of the MVVM Pattern" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/8662.MVVM_2D00_diagram_5F00_4DD0C075.png" width="570" height="321" /&gt;&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="100%" align="center"&gt;&lt;em&gt;Diagram of the MVVM Pattern&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;
  &lt;br clear="all" /&gt;Using the MVVM pattern, you can share models and view models across platforms using Portable Class Libraries.&amp;#160; When a model or view model needs to access non-portable functionality, you can create an abstraction for that functionality and implement it in platform-specific code.&amp;#160; The app for each platform will contain the views and reference the portable library, as shown in the following diagram.&lt;/p&gt;

&lt;table style="width: 100%" border="0" cellspacing="0" cellpadding="2"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td valign="top" width="100%" align="center"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Cross Platform App Project Structure with Portable Class Libraries and MVVM" border="0" alt="Cross Platform App Project Structure with Portable Class Libraries and MVVM" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/0333.Cross_2D00_platform_2D00_app_2D00_architecture_5F00_18C43145.png" width="570" height="321" /&gt;&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="100%" align="center"&gt;&lt;em&gt;Cross Platform App Project Structure with Portable Class Libraries and MVVM&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;
  &lt;br clear="all" /&gt;A simple example of a cross platform app that uses portable libraries and MVVM can be found in this &lt;a href="http://sdrv.ms/MluUOH"&gt;PortableNotepad sample&lt;/a&gt;.&amp;#160; In that app, the view model needs access to an instance of IFileStorage, so it takes it as a constructor parameter.&amp;#160; The view’s constructor creates the view model, passing in the platform-specific implementation of IFileStorage, and sets the view’s DataContext to the view model it created.&lt;/p&gt;

&lt;p&gt;For more complicated apps, it can get messy passing the implementations for the platform specific functionality down into portable code.&amp;#160; One solution to this is a simple “service locator” in the portable library with static properties corresponding to the portable abstractions, which get set during app startup.&amp;#160; Portable code can then access the non-portable functionality through the service locator class.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class ServiceLocator
{
    public static IFileStorage FileStorage { get; set; }
    public static IPhotoChooser PhotoChooser { get; set; }
}&lt;/pre&gt;

&lt;p&gt;Of course, using static properties like this may raise “singleton pattern” alarm bells, and will make it harder to write unit tests for your code.&amp;#160; So you may want to use an IoC container, as hooking up dependencies while maintaining testability and separation of concerns is what IoC containers are designed to do.&amp;#160; &lt;a href="http://code.google.com/p/autofac/"&gt;Autofac&lt;/a&gt; is one IoC container which has a portable version, and there’s also a &lt;a href="https://github.com/onovotny/ninject"&gt;portable fork of Ninject&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;David Kean’s MSDN article on &lt;a href="http://msdn.microsoft.com/en-us/magazine/hh852593.aspx"&gt;Creating a Continuous Client Using Portable Class Libraries&lt;/a&gt; includes a sample which demonstrates a more complex cross platform app which uses portable libraries and MVVM.&amp;#160; The sample is a shopping list app called OnYourWayHome and has a Windows Phone 7 and a Windows Store app version.&amp;#160; It shows how you can handle navigation between pages, use an IoC container, and use Azure Service bus to sync state between multiple clients.&amp;#160; The version from the MSDN article is based on the VS 2012 Beta and Windows 8 Consumer Preview, so it will need some updates to run on Windows 8 RTM.&amp;#160; An updated version of the app which uses MEF Lightweight composition (instead of Autofac) is included as a sample in the &lt;a href="http://mef.codeplex.com/SourceControl/list/changesets"&gt;MEF source code&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Another sample app is &lt;a href="http://sdrv.ms/OZ3GuK"&gt;Contoso Helpdesk&lt;/a&gt;, which I’ve been using in presentations about Portable Class Libraries.&amp;#160; This app uses the same architecture (and much of the same code) as the OnYourWayHome sample.&amp;#160; Like OnYourWayHome, it has a Windows Phone 7 and Windows Store app version, but instead of a shopping list, it keeps track of helpdesk tickets.&amp;#160; In Contoso Helpdesk, I’ve factored out the MVVM infrastructure pieces which could be reused in other apps into a library called MvvmPortable.&amp;#160; You can use this library as a starting point to write your own cross platform apps.&lt;/p&gt;

&lt;h1&gt;Reusable Portable Libraries&lt;/h1&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;p&gt;If you are creating a library for others to use (such as an open source library), you probably want to make it as easy as possible to reference and use your library.&amp;#160; That means consumers of the library should be able to add a reference to it as a single unit.&amp;#160; Some libraries won’t need any non-portable functionality, so you can create a single portable DLL.&amp;#160; &lt;a href="http://code.google.com/p/autofac/"&gt;Autofac&lt;/a&gt; and &lt;a href="http://json.codeplex.com/"&gt;Json.NET&lt;/a&gt; are two libraries which have done this.&amp;#160; For libraries that need to be factored into multiple DLLs (for example a portable and a platform specific part), publishing them as &lt;a href="http://nuget.org/"&gt;NuGet&lt;/a&gt; packages allows consumers to reference the different components of the library as one unit.&amp;#160; (NuGet also makes it a lot easier to consume a library that consists of a single assembly, so either way I recommend publishing your libraries on NuGet.)&lt;/p&gt;

&lt;p&gt;The code to use your library should also be simple.&amp;#160; That means the project referencing your library shouldn’t have to manage hooking up the platform specific part of your library with the portable part.&amp;#160; One way to do this is to have an initialize method in your platform specific part of your library which passes references to platform specific implementations down to the portable part of your library.&amp;#160; Here’s an example of what this could look like:&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;public class MyLibraryPhoneUtil
{
    public static void Initialize()
    {
        MyLibraryServiceLocator.FileStorage = new PhoneFileStorage();
        MyLibraryServiceLocator.PhotoChooser = new PhonePhotoChooser();
    }
}&lt;/pre&gt;

&lt;p&gt;This is simple for you as a library author to write, but it means that consumers of your library need to call the initialize method on startup.&lt;/p&gt;

&lt;p&gt;For consumers of your library, it will be easier if the portable part of your library connects to the platform specific part with no action required on their part.&amp;#160; You can do this by having the portable part load the platform-specific part by calling Assembly.Load(), and using reflection to get the functionality it needs.&amp;#160; For an example of how to do this, see&amp;#160; the &lt;a href="http://pclcontrib.codeplex.com/"&gt;Portable Class Libraries Contrib&lt;/a&gt; project.&amp;#160; The code which handles this functionality is in the Source\Portable.Runtime\Adaptation folder.&amp;#160; The &lt;a href="http://msdn.microsoft.com/en-us/data/gg577609.aspx"&gt;Reactive Extensions&lt;/a&gt; (Rx) also use this method to connect their portable System.Reactive.Core assembly with the platform-specific System.Reactive.PlatformServices assembly.&amp;#160; Speaking of Reactive Extensions, the team’s blog posts announcing Rx 2.0 &lt;a href="http://blogs.msdn.com/b/rxteam/archive/2012/03/12/reactive-extensions-v2-0-beta-available-now.aspx"&gt;Beta&lt;/a&gt;, &lt;a href="http://blogs.msdn.com/b/rxteam/archive/2012/06/20/reactive-extensions-v2-0-release-candidate-available-now.aspx"&gt;RC&lt;/a&gt;, and &lt;a href="http://blogs.msdn.com/b/rxteam/archive/2012/08/15/reactive-extensions-v2-0-has-arrived.aspx"&gt;RTM&lt;/a&gt; cover how they converted Rx to support Portable Class Libraries, and are a great case study for how to do so with a large existing library.&lt;/p&gt;

&lt;p&gt;Another option is to use reflection to call platform-specific APIs from a portable library directly.&amp;#160; This can be a good choice for a library which can be almost entirely portable, but which has a small, isolated set of platform-specific functionality it needs to access.&amp;#160; This &lt;a href="http://mvvmlight.codeplex.com/SourceControl/network/forks/onovotny/MvvmLightPortable"&gt;portable fork of MVVM Light&lt;/a&gt; uses this method in the ViewModelBase class to determine whether it is running in the designer.&lt;/p&gt;

&lt;h1&gt;Doing the Impossible&lt;/h1&gt;

&lt;p&gt;Portable libraries can’t reference non-portable libraries, because anything a portable library references needs to run on the same platforms the portable library supports.&amp;#160; But what if there is a library that is supported on all the platforms a portable library needs, it just has a separate DLL for each platform instead of being implemented as a Portable Class Library?&amp;#160; Wouldn’t it be nice if you could reference that library from a portable library?&amp;#160; With a bit of work, you can.&lt;/p&gt;

&lt;p&gt;To use a concrete example, let’s imagine there’s a .NET library for sqlite that you would like to use from a portable library.&amp;#160; The trick is to reference one assembly when compiling, and deploy a different one to be used at runtime.&amp;#160; You can create a portable library with the same API surface and assembly identity as the sqlite library.&amp;#160; This is your “reference assembly.”&amp;#160; This assembly should never be used at runtime, so you don’t actually have to implement anything—just throw NotImplementedExceptions in all methods.&amp;#160; Then a portable library can reference and compile against the reference assembly version of the sqlite library.&amp;#160; Apps that use the portable library can reference the normal implementation of the sqlite library for the platform they target, which will cause that version of the sqlite library to be packaged with the app and used at runtime.&lt;/p&gt;

&lt;p&gt;I don’t know of any projects that are currently using this strategy, and I’m not sure if overall it’s likely to be a better solution than creating a portable abstraction like I described previously.&amp;#160; Still, it’s an interesting option.&amp;#160; I’d love to hear how it works for you if you do try using it.&amp;#160; If it turns out to be a useful pattern we can consider providing more tooling to support it.&lt;/p&gt;

&lt;h1&gt;Conclusion&lt;/h1&gt;

&lt;p&gt;Using the patterns I’ve described, Portable Class Libraries can be used for a wide variety of projects, both for cross platform apps and general purpose reusable libraries.&amp;#160; Of course, the fact that these patterns are needed in the first place means that using portable libraries can be more complicated than writing code for a single platform.&amp;#160; If you want to target multiple platforms, however, you will have to deal with additional complexity somehow.&amp;#160; You can choose to keep entirely separate code bases; share your code with linked source files, separate projects for each platform, and conditional compilation; or use portable libraries to share code between platforms.&amp;#160; There are advantages and disadvantages to each of these options.&amp;#160; I think in many cases, portable libraries are a great choice—they avoid the project proliferation problem and make it easier to share code in a way that will be maintainable in the long run.&lt;/p&gt;

&lt;table border="0" cellspacing="0" cellpadding="2" width="100%"&gt;&lt;tbody&gt;
    &lt;tr&gt;
      &lt;td valign="top" width="100%" align="center"&gt;&lt;a href="http://slodge.blogspot.com/2012/05/portable-class-libraries-in-mvvmcross.html"&gt;&lt;img style="background-image: none; border-right-width: 0px; padding-left: 0px; padding-right: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px; padding-top: 0px" title="Portable Class Library solution structure sample from MvvmCross" border="0" alt="Portable Class Library solution structure sample from MvvmCross" src="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-blogs-components-weblogfiles/00-00-01-12-25-metablogapi/0741.TwitterSearch_2D00_Portable_2D00_Class_2D00_Library_2D00_Solution_2D00_Structure_5F00_6625FDE3.png" width="560" height="340" /&gt;&lt;/a&gt;&lt;/td&gt;
    &lt;/tr&gt;

    &lt;tr&gt;
      &lt;td valign="top" width="100%" align="center"&gt;&lt;em&gt;Sample of how Portable Class Libraries can simplify the solution structure for a cross platform app – &lt;a href="http://slodge.blogspot.com/2012/05/portable-class-libraries-in-mvvmcross.html"&gt;MvvmCross&lt;/a&gt;&lt;/em&gt;&lt;/td&gt;
    &lt;/tr&gt;
  &lt;/tbody&gt;&lt;/table&gt;

&lt;p&gt;
  &lt;br clear="all" /&gt;The functionality supported in portable libraries will continue to grow over time.&amp;#160; At the beginning of 2011, we &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2011/01/19/announcing-portable-library-tools-ctp-justin-van-patten.aspx"&gt;released&lt;/a&gt; the first version of Portable Class Library support as an add-in for Visual Studio 2010 with support for a fairly limited set of APIs.&amp;#160; With the Visual Studio 2012 release, we now support &lt;a href="http://blogs.msdn.com/b/bclteam/archive/2012/05/09/announcing-portable-library-tools-2-beta-for-visual-studio-2010.aspx"&gt;much more functionality&lt;/a&gt; (which is also now available in the add-in for Visual Studio 2010).&amp;#160; We will continue to work on making more code portable across more platforms using portable libraries.&amp;#160; We also hope to see third-party libraries which provide portable abstractions and implementations for you so you have less work to do when writing a cross-platform app (Sqlite and &lt;a href="http://xamarin.com/mobileapi"&gt;Xamarin.Mobile&lt;/a&gt; would be great candidates for this).&lt;/p&gt;

&lt;p&gt;We’d also love to hear your feedback.&amp;#160; We hope you will try using Portable Class Libraries and let us know what problems you run into and what seems to be more difficult than it should be.&amp;#160; This will help us know what to focus on for future improvements.&amp;#160; You can leave a comment on this blog post or contact &lt;a href="https://twitter.com/davkean"&gt;David Kean&lt;/a&gt; and &lt;a href="https://twitter.com/dsplaisted"&gt;me&lt;/a&gt; on Twitter.&lt;/p&gt;

&lt;p&gt;For more information on Portable Class Libraries, see this &lt;a href="http://blogs.msdn.com/b/dotnet/archive/2012/07/06/targeting-multiple-platforms-with-portable-code-overview.aspx"&gt;Overview of Portable Class Libraries&lt;/a&gt; on the .NET Framework Blog, and the links from this Channel 9 &lt;a href="http://channel9.msdn.com/Shows/Visual-Studio-Toolbox/Visual-Studio-ToolboxPortable-Class-Libraries"&gt;Visual Studio Toolbox show on Portable Class Libraries&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10338853" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>How To Control Who Can Write Extensions For Your MEF Application</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2010/11/01/how-to-control-who-can-write-extensions-for-your-mef-application.aspx" /><link rel="enclosure" type="application/x-zip-compressed" length="19662" href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-08-44-06/StrongNameCatalog.zip" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2010/11/01/how-to-control-who-can-write-extensions-for-your-mef-application.aspx</id><published>2010-11-01T23:28:00Z</published><updated>2010-11-01T23:28:00Z</updated><content type="html">&lt;p&gt;With the MEF DirectoryCatalog, it is easy to load extensions from a given directory for a MEF Application.&amp;#160; The DirectoryCatalog will scan any assemblies in that directory and find MEF extensions in those assemblies.&amp;#160; This means that adding an extension to a MEF application can be as easy as dropping a DLL in an extensions folder.&lt;/p&gt;  &lt;p&gt;However, some people would like to have control over what extensions are allowed in their MEF application.&amp;#160; For example, in a commercial application you may want to offer additional optional add-ons for sale, but not allow third party extensibility.&amp;#160; In these situations, our recommendation is generally to use strong name signing with your assemblies, and only allow assemblies with the correct public key to be added to the catalog.&amp;#160; Doing so is not too complicated, but we haven’t actually provided code showing how to do so… until now.&lt;/p&gt;  &lt;p&gt;Below is the code for a MEF catalog which loads extensions from a directory, but ignores any assemblies where the public key doesn’t match one of the keys passed to the constructor.&amp;#160; You can also download the project, which also includes some simple tests.&lt;/p&gt;  &lt;pre class="brush: csharp; gutter: false; toolbar: false;"&gt;using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel.Composition.Primitives;
using System.IO;
using System.Reflection;

namespace System.ComponentModel.Composition.Hosting
{
    public class StrongNameCatalog : ComposablePartCatalog
    {
        AggregateCatalog _aggregateCatalog = new AggregateCatalog();

        public StrongNameCatalog(string path, params byte[][] trustedKeys)
        {
            foreach (var file in Directory.GetFiles(path))
            {
                AssemblyName assemblyName = null;
                try
                {
                    assemblyName = AssemblyName.GetAssemblyName(file);
                }
                catch (ArgumentException)
                {
                    //  According to MSDN, ArgumentException can be thrown
                    //  if the assembly file is invalid
                }
                catch (BadImageFormatException)
                {
                    //  Not a valid assembly
                }

                if (assemblyName != null)
                {
                    var publicKey = assemblyName.GetPublicKey();
                    if (publicKey != null)
                    {
                        bool trusted = false;
                        foreach (var trustedKey in trustedKeys)
                        {
                            if (assemblyName.GetPublicKey().SequenceEqual(trustedKey))
                            {
                                trusted = true;
                                break;
                            }
                        }

                        if (trusted)
                        {
                            _aggregateCatalog.Catalogs.Add(new AssemblyCatalog(file));
                        }
                    }
                }
            }
        }

        public override IQueryable&amp;lt;ComposablePartDefinition&amp;gt; Parts
        {
            get
            {
                return _aggregateCatalog.Parts;
            }
        }

        public override IEnumerable&amp;lt;Tuple&amp;lt;ComposablePartDefinition, ExportDefinition&amp;gt;&amp;gt;
            GetExports(ImportDefinition definition)
        {
            return _aggregateCatalog.GetExports(definition);
        }
    }
}&lt;/pre&gt;

&lt;h3&gt;A note about “Security”&lt;/h3&gt;

&lt;p&gt;When people talk about this functionality, they often describe it as a “secure” catalog.&amp;#160; I don’t think it’s a good idea to call this a secure catalog, because in most cases it doesn’t increase security.&amp;#160; If you are worried about malicious code being loaded from your extension directory, a machine is probably already compromised if an attacker can put an arbitrary file there.&amp;#160; And if you want to prevent people from writing their own extensions to your application, the strong name catalog will help deter them, but if they are determined they can modify your application to remove the strong name check.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10084406" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>How to Debug and Diagnose MEF Failures</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx" /><link rel="enclosure" type="application/x-zip-compressed" length="100707" href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-03-77-90/Composition.Diagnostics.zip" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx</id><published>2010-07-13T21:10:00Z</published><updated>2010-07-13T21:10:00Z</updated><content type="html">&lt;p&gt;The Managed Extensibility Framework (MEF) helps make it easy to write extensible applications.&amp;#160; We hope that it is simple to understand the basics and get started.&amp;#160; However, MEF brings with it the possibility of new types of failures.&amp;#160; Without the proper knowledge, these failures can be difficult to diagnose.&amp;#160; This blog post will cover some background information you need to understand when dealing with MEF failures, the common types of MEF failures, and how you can diagnose these issues.&lt;/p&gt;  &lt;h2&gt;Import Cardinality&lt;/h2&gt;  &lt;p&gt;MEF imports have one of three cardinalities.&amp;#160; A collection import has a cardinality of &lt;strong&gt;ZeroOrMore&lt;/strong&gt;.&amp;#160; MEF will supply all of the exports that match the import, whether there are zero, one, ten, or ten thousand.&amp;#160; The ImportManyAttribute is used to declare a collection import.&lt;/p&gt;  &lt;pre class="brush: csharp; gutter: false;"&gt;[ImportMany] 
public IEnumerable&amp;lt;IPlugin&amp;gt; Plugins { get; set; }&lt;/pre&gt;

&lt;p&gt;An import with a cardinality of &lt;strong&gt;ExactlyOne&lt;/strong&gt; only expects one export to satisfy it, and can be called a required import.&amp;#160; This can be declared with the ImportAttribute.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;[Import] 
public IPlugin Plugin { get; set; }&lt;/pre&gt;

&lt;p&gt;Finally, you can declare an optional import by setting the AllowDefault property of the ImportAttribute to true.&amp;#160; The cardinality of this import is &lt;strong&gt;ZeroOrOne&lt;/strong&gt;.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;[Import(AllowDefault=true)] 
public IPlugin Plugin { get; set; }&lt;/pre&gt;

&lt;h2&gt;Rejection&lt;/h2&gt;

&lt;p&gt;A part with an import with a cardinality of ZeroOrMore or ZeroOrOne does not have any specific requirements as to the number of exports that match the import.&amp;#160; The part should work when there are none available, when there is one, and when there are many.&amp;#160; On the other hand, an import with a cardinality of ExactlyOne is a declaration of a requirement that the part needs in order to function correctly.&amp;#160; If the import cannot be satisfied, MEF assumes the part cannot function correctly and will &lt;strong&gt;reject&lt;/strong&gt; the part, which means it will not be available at all in the container.&lt;/p&gt;

&lt;p&gt;A rejection can also be caused when there is more than one matching export.&amp;#160; MEF has no way to choose between multiple exports that match an import of cardinality ZeroOrOne or ExactlyOne.&amp;#160; So in this case, MEF will not use any of the matching exports.&amp;#160; The part will be rejected if the import cardinality was ExactlyOne, and the import will be set to null if the cardinality was ZeroOrOne.&amp;#160; If this behavior is not what you want, see these blog posts on &lt;a href="http://blogs.msdn.com/b/dsplaisted/archive/2009/08/10/import-cardinality-and-picking-which-export-to-use.aspx"&gt;Picking an Export&lt;/a&gt; and &lt;a href="http://blogs.msdn.com/b/gblock/archive/2009/05/14/customizing-container-behavior-part-2-of-n-defaults.aspx"&gt;Using Defaults with MEF&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Rejection makes it simpler to write parts, because they can simply assume that their imports with a cardinality of ExactlyOne will be available instead of writing code to handle the case where they aren’t.&amp;#160; However, rejection effectively makes parts disappear from the container, so it can be hard to figure out what is wrong if you don’t know to expect it.&amp;#160; Furthermore, a problem with one part can cause a chain of rejections.&amp;#160; Imagine you have part A which depends (via a required import) on part B, which depends on part C.&amp;#160; If part C has an import which can’t be satisfied, then it will be rejected, which will in turn cause part B and part A to be rejected.&amp;#160; The symptom of the problem will be that part A doesn’t show up in the container, but the root cause of the problem is with part C.&amp;#160; Without understanding rejection, you might look for a problem with part A, see that everything appears to be correct, and be unable to figure out why it isn’t showing up.&lt;/p&gt;

&lt;h2&gt;Failures Where an Export is not Available&lt;/h2&gt;

&lt;p&gt;A common type of MEF failure is when an export is not available.&amp;#160; The symptoms of this failure can either be that the export is missing from a collection import you expected it to be present in, or that the container throws an exception when you attempt to access it.&amp;#160; In the first case, since the export was not required, this is not a composition error as far as MEF is concerned, and your application will often continue to run, albeit without the functionality that the missing export provided.&amp;#160; In the second case, MEF is unable to satisfy a request you have made of it.&amp;#160; For example, if you call container.GetExport&amp;lt;IFoo&amp;gt;() and there is no IFoo export available, the container will throw a CardinalityMismatchException.&amp;#160; Likewise, an exception will be thrown if you call CompositionInitializer.SatisfyImports(), passing in a part that has an import that cannot be satisfied.&lt;/p&gt;

&lt;p&gt;There are several possible causes for an export not being available.&lt;/p&gt;

&lt;h4&gt;There is no export&lt;/h4&gt;

&lt;p&gt;The export may simply not exist.&amp;#160; This can happen if you forget to add an ExportAttribute to your class.&lt;/p&gt;

&lt;h4&gt;The part providing the export is not in the catalog&lt;/h4&gt;

&lt;p&gt;If a part is not in the catalog, then its exports will not be available.&amp;#160; This can happen if the corresponding assembly was not placed in the correct folder, if it was out of date, or if there was an error loading the assembly (for example, if it references an assembly that is not available).&amp;#160; The application may not be set up to include the assembly providing the export in the catalog.&amp;#160; It is also possible that the type has a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.partnotdiscoverableattribute.aspx"&gt;PartNotDiscoverableAttribute&lt;/a&gt; on it, preventing it from showing up in the catalog, or that the type is abstract, or that the export is on a base/ancestor type and not the actual type which is in the catalog.&lt;/p&gt;

&lt;h4&gt;The export does not match the import&lt;/h4&gt;

&lt;p&gt;The export may be in the catalog and available in the container, but if it doesn’t match an import, then it won’t be used to satisfy that import.&amp;#160; An easy way for this to happen is to put an export attribute on a class without specifying the contract. Consider the following two exports&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;[Export]
public class Plugin1 : IPlugin { }

[Export(typeof(IPlugin))]
public class Plugin2 : IPlugin { }&lt;/pre&gt;

&lt;p&gt;The contract for the first export is the Plugin1 class, not the IPlugin interface, and so it wouldn’t match an import of IPlugin.&amp;#160; The second export specifies that the IPlugin interface is the contract for the export, and would match an IPlugin import.&lt;/p&gt;

&lt;p&gt;Here is a list of issues that can prevent an export from matching an import:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Contract name doesn’t match &lt;/li&gt;

  &lt;li&gt;Export type identity doesn’t match &lt;/li&gt;

  &lt;li&gt;Metadata doesn’t match 
    &lt;ul&gt;
      &lt;li&gt;Metadata key is not present &lt;/li&gt;

      &lt;li&gt;Metadata value is not of correct type &lt;/li&gt;
    &lt;/ul&gt;
  &lt;/li&gt;

  &lt;li&gt;Creation policy doesn’t match &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Under the hood, a MEF import uses a constraint which takes an &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.primitives.exportdefinition.aspx"&gt;ExportDefinition&lt;/a&gt; and returns a boolean value indicating whether the export matches the import.&amp;#160; This constraint is represented as an expression, and you may see these constraints when debugging MEF or using tools to analyze MEF parts.&amp;#160; A typical import constraint looks like this:&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;exportDefinition =&amp;gt; ((exportDefinition.ContractName == &amp;quot;MEFSample.IPlugin&amp;quot;)
    AndAlso (exportDefinition.Metadata.ContainsKey(&amp;quot;ExportTypeIdentity&amp;quot;)
    AndAlso &amp;quot;MEFSample.IPlugin&amp;quot;.Equals(exportDefinition.Metadata.get_Item(&amp;quot;ExportTypeIdentity&amp;quot;))))&lt;/pre&gt;

&lt;p&gt;The constraint requires both the contract name and the exported type (which is stored under the metadata key “ExportTypeIdentity”) to match.&amp;#160; In many cases, you won’t specify a contract name, and the contract name and the export type identity will be the same.&amp;#160; However, if you do specify the contract name, you can still have a type identity mismatch.&amp;#160; The following code is an example of this—the export type identity is the Plugin class, but it would need to be the IPlugin interface to match the import.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;[Export(&amp;quot;SpecialPlugin&amp;quot;)]
public class Plugin : IPlugin { }

public class Importer
{
    [Import(&amp;quot;SpecialPlugin&amp;quot;)]
    public IPlugin SpecialPlugin { get; set; }
}&lt;/pre&gt;

&lt;p&gt;Using an interface to access MEF metadata values adds additional requirements to the constraint.&amp;#160; For each property in the metadata view interface, an export must have a metadata item with a name matching the name of the property, and the value needs to be of the type of the property.&amp;#160; To make a piece of metadata optional, you can put a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx"&gt;DefaultValueAttribute&lt;/a&gt; on the property in the interface.&amp;#160; If the following metadata interface is used on an import, then only exports which have metadata with the name “Name” with a value of type string will match the import, but the exports won’t need to have a piece of metadata with the name “Priority”.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;public interface IPluginMetadata
{
    string Name { get; }
    [DefaultValue(0)]
    int Priority { get; }
}&lt;/pre&gt;

&lt;p&gt;Finally, an importer can specify a required creation policy (using the RequiredCreationPolicy properties of the Import and ImportMany attributes).&amp;#160; Also, using an &lt;a href="http://msdn.microsoft.com/en-us/library/ff382807(v=VS.95).aspx"&gt;ExportFactory&lt;/a&gt; (currently only available in the Silverlight version of MEF) will set the required creation policy to NonShared.&amp;#160; If the export comes from a part with an incompatible creation policy, it won’t match.&lt;/p&gt;

&lt;h4&gt;The part providing the export is rejected&lt;/h4&gt;

&lt;p&gt;If a part is rejected, its exports will not be available.&amp;#160; As covered in the rejection section, a part will be rejected if there are no exports available to satisfy any of its required imports, or because there are more than one that could satisfy it.&amp;#160; If there aren’t any exports available, this can be for any of the reasons for an export not to be available—there may be no export, the part providing the export might not be in the catalog, the export you think should satisfy the import might not actually match, and the part providing the export could be rejected.&amp;#160; There may be a chain of rejections, and at the end of it will be the root cause of the problem which needs to be fixed in order to make the original export available (as well as all of the intermediate ones in the chain).&lt;/p&gt;

&lt;h2&gt;Recomposition Failures&lt;/h2&gt;

&lt;p&gt;Another type of failure in MEF is a recomposition failure.&amp;#160; MEF supports recomposition, which means that you can change the parts that are available in the container while the application is running, and the container will update the composition graph.&amp;#160; This lets you add new extensions at runtime which is especially useful in Silverlight applications for keeping the initial download small and downloading additional functionality after the application starts.&amp;#160; However, imports have to opt in to recomposition to allow MEF to add or remove exports after the part has been initialized.&amp;#160; If they don’t, or if the recomposition would violate other MEF guarantees (such as import cardinality), MEF will cancel the change by throwing a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.changerejectedexception.aspx"&gt;ChangeRejectedException&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;The operations which cause recomposition (and hence can throw a ChangeRejectedException) are:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Modifying an &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aggregatecatalog.aspx"&gt;AggregateCatalog&lt;/a&gt; by adding or removing a catalog in the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.aggregatecatalog.catalogs.aspx"&gt;Catalogs&lt;/a&gt; collection &lt;/li&gt;

  &lt;li&gt;Calling the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog.refresh.aspx"&gt;DirectoryCatalog.Refresh&lt;/a&gt; method &lt;/li&gt;

  &lt;li&gt;Calling the container’s &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.compositioncontainer.compose.aspx"&gt;Compose&lt;/a&gt; method, or the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.attributedmodelservices.composeparts.aspx"&gt;ComposeParts&lt;/a&gt; or &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.attributedmodelservices.composeexportedvalue.aspx"&gt;ComposeExportedValue&lt;/a&gt; extension methods &lt;/li&gt;

  &lt;li&gt;Downloading a XAP with a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.deploymentcatalog(VS.95).aspx"&gt;DeploymentCatalog&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Recomposition with a DeploymentCatalog is different than the other methods of recomposition in that the ChangeRejectedException won’t be thrown from a method you call.&amp;#160; The DeploymentCatalog starts downloading the XAP asynchronously when you call the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.deploymentcatalog.downloadasync(v=VS.95).aspx"&gt;DownloadAsync&lt;/a&gt; method, and when the download completes it triggers recomposition and reports the result by raising the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.deploymentcatalog.downloadcompleted(v=VS.95).aspx"&gt;DownloadCompleted&lt;/a&gt; event.&amp;#160; If the change is rejected, then the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.asynccompletedeventargs.error(v=VS.95).aspx"&gt;Error&lt;/a&gt; property of the event args will be set to the ChangeRejectedException.&lt;/p&gt;

&lt;h2&gt;Assembly Load Issues&lt;/h2&gt;

&lt;p&gt;In .NET, there are different contexts into which an assembly can be loaded.&amp;#160; The default load context is generally the best one to use, but it cannot load assemblies that are not in the application base directory, subdirectories of the application base which are included in the probing path, or the GAC.&amp;#160; When using a &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.directorycatalog.aspx"&gt;DirectoryCatalog&lt;/a&gt; or passing a path to the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.assemblycatalog.aspx"&gt;AssemblyCatalog&lt;/a&gt; constructor, MEF will attempt to load assemblies in the default load context.&amp;#160; However, if the assemblies are not in the probing path or the GAC, this will not be possible, and MEF will load them in the load-from context instead.&lt;/p&gt;

&lt;p&gt;The load-from context can lead to type identity issues that result in an InvalidCastException, MissingMethodException, or other errors.&amp;#160; In order to avoid these issues in a MEF application, you can put any extension directories under the application base directory, and &lt;a href="http://msdn.microsoft.com/en-us/library/823z9h8w.aspx"&gt;add them to the probing private path&lt;/a&gt; in your &lt;a href="http://msdn.microsoft.com/en-us/library/ms229689(VS.90).aspx"&gt;application configuration file&lt;/a&gt;.&amp;#160; For other options and more information about assembly loading in .NET, see the &lt;a href="http://msdn.microsoft.com/en-us/library/dd153782.aspx"&gt;Best Practices for Assembly Loading&lt;/a&gt; MSDN document.&lt;/p&gt;

&lt;h1&gt;Methods and Tools for Investigating MEF Failures&lt;/h1&gt;

&lt;h4&gt;&amp;#160;&lt;/h4&gt;

&lt;h2&gt;Inspecting the catalog in the debugger&lt;/h2&gt;

&lt;p&gt;A simple way of debugging a MEF application is to inspect the catalog in the Visual Studio debugger while the application is running.&amp;#160; You can look at the Parts property to see what parts are in the catalog.&amp;#160; This will help you verify that MEF is actually finding the parts you expect it to.&amp;#160; You can also drill down and examine the ImportDefinitions and ExportDefinitions properties of each part to see its imports and exports.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-12-25-metablogapi/4062.Catalog_5F00_debugging_5F00_26BAF21C.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Inspecting the Parts property of a MEF catalog in the Visual Studio debugger" border="0" alt="Inspecting the Parts property of a MEF catalog in the Visual Studio debugger" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-12-25-metablogapi/6644.Catalog_5F00_debugging_5F00_thumb_5F00_5EF96934.png" width="399" height="157" /&gt;&lt;/a&gt;&amp;#160;&lt;/p&gt;

&lt;h2&gt;Rejection trace messages&lt;/h2&gt;

&lt;p&gt;MEF uses standard &lt;a href="http://msdn.microsoft.com/en-us/library/6da106y8(v=VS.85).aspx"&gt;.NET tracing&lt;/a&gt; to report parts which are rejected.&amp;#160; When a part is rejected, it will trace a message which includes the name of the rejected part, the reason for the rejection, and the import which caused the rejection.&amp;#160; An example of a rejection trace message is shown below, with the most important parts in bold.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;System.ComponentModel.Composition Warning: 1 : The ComposablePartDefinition &lt;strong&gt;'MEFConsole.PrintCommand' has been rejected&lt;/strong&gt;. The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information. &lt;/p&gt;

  &lt;p&gt;1) &lt;strong&gt;No valid exports were found that match the constraint '((exportDefinition.ContractName == &amp;quot;MEFConsole.IPrinterService&amp;quot;)&lt;/strong&gt; AndAlso (exportDefinition.Metadata.ContainsKey(&amp;quot;ExportTypeIdentity&amp;quot;) AndAlso &amp;quot;MEFConsole.IPrinterService&amp;quot;.Equals(exportDefinition.Metadata.get_Item(&amp;quot;ExportTypeIdentity&amp;quot;))))', invalid exports may have been rejected. &lt;/p&gt;

  &lt;p&gt;&lt;strong&gt;Resulting in: Cannot set import 'MEFConsole.PrintCommand.PrintService&lt;/strong&gt; (ContractName=&amp;quot;MEFConsole.IPrinterService&amp;quot;)' on part 'MEFConsole.PrintCommand'. 

    &lt;br /&gt;Element: MEFConsole.PrintCommand.PrintService (ContractName=&amp;quot;MEFConsole.IPrinterService&amp;quot;) --&amp;gt;&amp;#160; MEFConsole.PrintCommand --&amp;gt;&amp;#160; AssemblyCatalog (Assembly=&amp;quot;MEFConsole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&amp;quot;)&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;When debugging an application in Visual Studio, these trace messages will be shown in the output window.&amp;#160; You can enable MEF tracing in an application that is not being debugged by adding a trace listener to the System.ComponentModel.Composition source in your &lt;a href="http://msdn.microsoft.com/en-us/library/ms229689(VS.90).aspx"&gt;application configuration file&lt;/a&gt;.&amp;#160; Below is an example of how to log MEF trace information to a log file.&lt;/p&gt;

&lt;pre class="brush: xml; gutter: false;"&gt;&amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;
&amp;lt;configuration&amp;gt;
    &amp;lt;system.diagnostics&amp;gt;
        &amp;lt;sources&amp;gt;
            &amp;lt;source name=&amp;quot;System.ComponentModel.Composition&amp;quot;
                    switchValue=&amp;quot;All&amp;quot;&amp;gt;
                &amp;lt;listeners&amp;gt;
                    &amp;lt;add name=&amp;quot;fileListener&amp;quot;
                         type=&amp;quot;System.Diagnostics.TextWriterTraceListener&amp;quot;
                         initializeData=&amp;quot;composition.log&amp;quot; /&amp;gt;
                &amp;lt;/listeners&amp;gt;
            &amp;lt;/source&amp;gt;
        &amp;lt;/sources&amp;gt;
        &amp;lt;trace autoflush=&amp;quot;true&amp;quot; indentsize=&amp;quot;4&amp;quot; /&amp;gt;
    &amp;lt;/system.diagnostics&amp;gt;
&amp;lt;/configuration&amp;gt;&lt;/pre&gt;

&lt;p&gt;MEF doesn’t examine parts to determine if they are rejected until it needs to in order to fulfill a request to the container.&amp;#160; This means that the rejection won’t be traced until the point in the program’s execution where an export of the part would be supplied.&amp;#160; Also, due to the details of how MEF implements composition, there are a lot of cases where the container doesn’t definitively determine whether a part is rejected, and so it doesn’t send a trace message.&amp;#160; In practice, this means that when there is a chain of rejections, only the part at the end of the chain (the opposite end from the root cause) will be traced as rejected, and no rejections at all will be traced when calling the container’s &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.hosting.compositioncontainer.compose.aspx"&gt;Compose&lt;/a&gt; method or the &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.composition.attributedmodelservices.composeparts.aspx"&gt;ComposeParts&lt;/a&gt; extension method.&amp;#160; These limitations mean that tracing can be helpful in detecting that you have a rejection, but will often not give you all the information you need to determine the problem.&lt;/p&gt;

&lt;h2&gt;Composition Diagnostics with Mefx&lt;/h2&gt;

&lt;p&gt;The Managed Extensibility Framework Explorer (Mefx) is a command line tool that you can use to diagnose a wide variety of MEF issues.&amp;#160; It can display information about MEF parts, determine which parts will be rejected, analyze the root cause for a rejection, and diagnose mismatches between exports and imports.&lt;/p&gt;

&lt;p&gt;When using Mefx, you specify what assemblies should be examined for MEF parts with the /file and /dir parameters.&amp;#160; Then you use one of the possible action parameters to specify what should be displayed.&amp;#160; The /parts parameter lists all of the parts found.&amp;#160; The /rejected parameter lists the parts which will be rejected.&amp;#160; The /causes command helps find root causes—it lists “primary rejections,��� parts that are rejected due to errors not related to the rejection of other parts.&amp;#160; Here are some samples of using Mefx, with the output shown in italics:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;gt; mefx /file:MefConsole.exe /parts 
    &lt;br /&gt;&lt;em&gt;MEFConsole.GreetCommand 
      &lt;br /&gt;MEFConsole.PrintCommand 

      &lt;br /&gt;MEFConsole.PrintService 

      &lt;br /&gt;MEFConsole.Program&lt;/em&gt; &lt;/p&gt;

  &lt;p&gt;&amp;gt; mefx /file:MefConsole.exe /rejected 
    &lt;br /&gt;&lt;em&gt;MEFConsole.PrintCommand 
      &lt;br /&gt;MEFConsole.PrintService&lt;/em&gt; &lt;/p&gt;

  &lt;p&gt;&amp;gt; mefx /file:MefConsole.exe /causes 
    &lt;br /&gt;&lt;em&gt;MEFConsole.PrintService&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In these samples, the PrintCommand and the PrintService were both rejected, but the PrintService was the root cause of the problem.&amp;#160; The /verbose parameter can be used to display detailed information about parts, including a list of their exports and imports.&amp;#160; Along with each import the /verbose parameter will show any exports that satisfy the import, any errors with the import, and any “unsuitable” exports—exports that have the same contract name as the import, but don’t match it for some other reason.&amp;#160; Using the /verbose parameter to the /causes command will give the following output, which indicates that the reason PrintService was rejected was because it had an import for IPrintSpooler, for which there was no export available:&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;[Part] MEFConsole.PrintService from: AssemblyCatalog (Assembly=&amp;quot;MEFConsole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&amp;quot;) 
    &lt;br /&gt;&amp;#160; [Primary Rejection] 

    &lt;br /&gt;&amp;#160; [Export] MEFConsole.PrintService (ContractName=&amp;quot;MEFConsole.IPrinterService&amp;quot;) 

    &lt;br /&gt;&amp;#160; [Import] MEFConsole.PrintService.Spooler (ContractName=&amp;quot;MEFConsole.IPrintSpooler&amp;quot;) 

    &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Exception] System.ComponentModel.Composition.ImportCardinalityMismatchException: No valid exports were found that match the constraint '((exportDefinition.ContractName == &amp;quot;MEFConsole.IPrintSpooler&amp;quot;) AndAlso (exportDefinition.Metadata.ContainsKey(&amp;quot;ExportTypeIdentity&amp;quot;) AndAlso &amp;quot;MEFConsole.IPrintSpooler&amp;quot;.Equals(exportDefinition.Metadata.get_Item(&amp;quot;ExportTypeIdentity&amp;quot;))))', invalid exports may have been rejected.&amp;#160; &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;You can also display information about a single part with the /type parameter.&amp;#160; To figure out why an export isn’t being supplied to an import, use the /type parameter with the type name for the part that has the import, together with the /verbose parameter.&amp;#160; In the below example, this shows that there are two exports with the same contract name as the Commands import, but that the second of them is missing the required metadata for the Name.&lt;/p&gt;

&lt;blockquote&gt;
  &lt;p&gt;&amp;gt; mefx /file:MEFConsole.exe /type:MEFConsole.Program /verbose 
    &lt;br /&gt;&lt;em&gt;[Part] MEFConsole.Program from: AssemblyCatalog (Assembly=&amp;quot;MEFConsole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&amp;quot;) 
      &lt;br /&gt;&amp;#160; [Export] MEFConsole.Program (ContractName=&amp;quot;MEFConsole.Program&amp;quot;) 

      &lt;br /&gt;&amp;#160; [Import] MEFConsole.Program.Commands (ContractName=&amp;quot;MEFConsole.ICommand&amp;quot;) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [SatisfiedBy] MEFConsole.PrintCommand (ContractName=&amp;quot;MEFConsole.ICommand&amp;quot;) from: MEFConsole.PrintCommand from: AssemblyCatalog (Assembly=&amp;quot;MEFConsole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&amp;quot;) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160; [Unsuitable] MEFConsole.GreetCommand (ContractName=&amp;quot;MEFConsole.ICommand&amp;quot;) from: MEFConsole.GreetCommand from: AssemblyCatalog (Assembly=&amp;quot;MEFConsole, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null&amp;quot;) 

      &lt;br /&gt;&amp;#160;&amp;#160;&amp;#160;&amp;#160;&amp;#160; [Because] RequiredMetadata, The import requires metadata '[Name, System.String]' but this is not provided by the export.&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Running Mefx without any arguments will display the full list of possible parameters.&amp;#160; More details about Mefx can be found in &lt;a href="http://msdn.microsoft.com/en-us/library/ff576068.aspx"&gt;this MSDN document&lt;/a&gt;.&lt;/p&gt;

&lt;h2&gt;Visual Mefx&lt;/h2&gt;

&lt;p&gt;Mefx is a command-line tool which runs on the full desktop .NET framework, and cannot analyze Silverlight applications.&amp;#160; Visual Mefx is a GUI-based version of Mefx, which runs under both Silverlight and desktop .NET.&amp;#160; It shows a list of parts in the left pane, and the details of the selected part in the right pane.&amp;#160; The parts are color-coded according to their rejection status: non-rejected parts use green, primary rejections use red, and non-primary rejections use yellow.&amp;#160; Below is a screenshot of Visual Mefx analyzing the same PrintCommand/PrintService rejection issue that we saw earlier.&lt;/p&gt;

&lt;p&gt;&lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-12-25-metablogapi/1832.VisualMEFXRejection_5F00_5E8D363F.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Visual MEFX Rejection" border="0" alt="Visual MEFX Rejection" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-12-25-metablogapi/7624.VisualMEFXRejection_5F00_thumb_5F00_7D63AA1D.png" width="554" height="389" /&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h2&gt;Mefx Limitations&lt;/h2&gt;

&lt;p&gt;Mefx analyzes the parts from the files you specify.&amp;#160; If your application adds any parts or exports to the container, Mefx won’t know about them and the analysis it performs won’t match what happens in your application.&amp;#160; Other customizations to the container, such as using custom export providers or a hierarchy of scoped containers, will also prevent Mefx from accurately analyzing composition issues.&lt;/p&gt;

&lt;p&gt;However, you can integrate Mefx’s composition diagnostics functionality into your application to avoid these limitations.&amp;#160; Mefx and Visual Mefx both are built on top of a composition diagnostics library.&amp;#160; You can reference this library in your application, and use the functionality it provides to perform analysis on the container that your application uses, with any extra parts or customizations that you have made to it.&lt;/p&gt;

&lt;h2&gt;Mefx Credits and Download&lt;/h2&gt;

&lt;p&gt;Mefx and the composition diagnostics library was originally written by &lt;a href="http://nblumhardt.com/"&gt;Nicholas Blumhardt&lt;/a&gt; when he was on the MEF team and included in the &lt;a href="http://mef.codeplex.com/"&gt;MEF codeplex releases&lt;/a&gt;.&amp;#160; &lt;a href="http://xamlcoder.com/blog/"&gt;Joe McBride&lt;/a&gt; ported it to Silverlight and WPF as Visual MEFX.&amp;#160; I took his version and made some further improvements.&amp;#160; I plan to add Mefx to the community open source &lt;a href="http://mefcontrib.codeplex.com/"&gt;MefContrib&lt;/a&gt; project, but for now you can &lt;a href="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Components-PostAttachments/00-10-03-77-90/Composition.Diagnostics.zip"&gt;download Mefx and Visual Mefx here&lt;/a&gt;.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10037790" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>Presentation at TechEd North America 2010</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2010/05/27/presentation-at-teched-north-america-2010.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2010/05/27/presentation-at-teched-north-america-2010.aspx</id><published>2010-05-27T00:22:49Z</published><updated>2010-05-27T00:22:49Z</updated><content type="html">&lt;p&gt;&lt;a href="http://northamerica.msteched.com/"&gt;TechEd North America 2010&lt;/a&gt; is in a few weeks, and I will be giving a presentation on MEF.&amp;#160; Below is the session description:&lt;/p&gt;  &lt;blockquote&gt;   &lt;p&gt;DEV05-INT | What's Wrong with My .NET Extensible MEF Application?      &lt;br /&gt;Thursday, June 10 | 8:00 AM – 9:15 AM | Rm 347&lt;/p&gt;    &lt;p&gt;The Managed Extensibility Framework (MEF) is a powerful new technology that will allow users to create extensible applications (applications which can enable third parties to easily modify their behavior). In this session, we discuss what can cause your MEF application to fail, how to go about identifying the source of a failure, and how to subsequently fix it. We discuss the design considerations that impacted why MEF is susceptible to these failures, and how you can keep your code resilient to them.&lt;/p&gt; &lt;/blockquote&gt;  &lt;p&gt;As you can see, this isn’t another “Introduction to MEF” presentation.&amp;#160; There isn’t very much information available on how to diagnose problems that can occur when using MEF.&amp;#160; Trying to do so without the right knowledge can be frustrating.&amp;#160; So if you are going to be at Tech Ed, I highly recommend coming to this session even if you already know the basics of MEF.&lt;/p&gt;  &lt;p&gt;There is also another session on MEF earlier in the week which looks like it will be more of an introduction/overview.&amp;#160; The code for that session is DEV304.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10016005" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>Overriding MEF Metadata</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2010/04/01/overriding-mef-metadata.aspx" /><link rel="enclosure" type="application/x-zip-compressed" length="19385" href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-98-85-73/MetadataOverride.zip" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2010/04/01/overriding-mef-metadata.aspx</id><published>2010-04-01T04:49:00Z</published><updated>2010-04-01T04:49:00Z</updated><content type="html">&lt;P&gt;The Managed Extensibility Framework (MEF) is designed to allow open-ended extensibility.&amp;nbsp; It is easy to define a contract and load extensions which satisfy the contract.&amp;nbsp; This is accomplished with a collection import, which can look like this:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;[ImportMany]
public IPlugin[] Plugins { get; set; }&lt;/PRE&gt;
&lt;H1&gt;&lt;/H1&gt;
&lt;H3&gt;Extensions may need to be ordered or prioritized&lt;/H3&gt;
&lt;P&gt;Often, the importer will need a way to sort or prioritize the imported extensions.&amp;nbsp; If the extensions are displayed in a menu, the importer may want to control what order they appear in.&amp;nbsp; Or there may be multiple extensions which can be used, and the importer needs to choose the “best” one which can handle a given item.&amp;nbsp; For example, if extensions are used to provide UI controls for editing fields, there may be a generic editor which can edit all field types but only uses a simple textbox, and a specialized editor which only works on enums but provides a dropdown box for editing.&amp;nbsp; Both of these extensions &lt;EM&gt;could&lt;/EM&gt; be used to edit an enum, but it is better to use the more specialized one.&lt;/P&gt;
&lt;H3&gt;Defining MEF metadata on an export&lt;/H3&gt;
&lt;P&gt;One way to represent the priority of an extension is with MEF metadata.&amp;nbsp; The exporter can add metadata using the ExportMetadataAttribute like this:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;[Export(typeof(IPlugin))]
[ExportMetadata("Name", "PluginA")]
[ExportMetadata("Priority", 1)]
public class PluginA : IPlugin { /* ... */ }&lt;/PRE&gt;
&lt;P&gt;A custom export attribute can make this less verbose and add more compile-time checking.&amp;nbsp; With a custom export attribute, the export would look like this:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;[ExportPlugin("PluginA", Priority=1)]
public class PluginA : IPlugin&lt;/PRE&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;For details on how to create a custom export attribute, see the “Using a Custom Export Attribute” section of &lt;A href="http://mef.codeplex.com/wikipage?title=Exports%20and%20Metadata&amp;amp;ProjectName=mef" mce_href="http://mef.codeplex.com/wikipage?title=Exports%20and%20Metadata&amp;amp;ProjectName=mef"&gt;this page&lt;/A&gt;.&lt;/P&gt;
&lt;H3&gt;Using MEF metadata on the import side&lt;/H3&gt;
&lt;P&gt;To get access to MEF metadata, an importer can use an interface with properties corresponding to the metadata keys it wishes to access.&amp;nbsp; To access metadata for the name and priority, the following interface could be used:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;public interface IPluginMetadata
{
    string Name { get; }
    [DefaultValue(0)]
    int Priority { get; }
}&lt;/PRE&gt;
&lt;P&gt;To use the interface, an importer can import into a collection of Lazy&amp;lt;T, TMetadata&amp;gt;, like this:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;[ImportMany]
public Lazy&amp;lt;IPlugin, IPluginMetadata&amp;gt;[] Plugins { get; set; }&lt;/PRE&gt;
&lt;P&gt;Then plugins could be ordered by priority (highest to lowest) with the following LINQ expression:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;Plugins.OrderByDescending(lazy =&amp;gt; lazy.Metadata.Priority);&lt;/PRE&gt;
&lt;H3&gt;Overriding metadata&lt;/H3&gt;
&lt;P&gt;Using MEF metadata for the priority puts the responsibility of defining the priority on the extension author.&amp;nbsp; An advantage of this is that when extensions are added to the system, they can “just work” without having to configure the priority.&amp;nbsp; On the other hand, the metadata can’t be modified without recompiling an extension.&amp;nbsp; Extensions from different sources will likely have been developed without any knowledge of each other, so the priority they provide may not be what is desired when they are used together.&lt;/P&gt;
&lt;P&gt;So it would be useful to be able to override the metadata that is supplied with an extension.&amp;nbsp; I’ve prototyped a catalog that allows you to do this.&amp;nbsp; You create it as a wrapper around another MEF catalog, and then you tell it what metadata should be overridden before creating your container.&amp;nbsp; The following code creates a catalog and then sets the priority of exports from the PluginA class to 5:&lt;/P&gt;&lt;PRE class="brush: csharp; gutter: false;"&gt;var catalog = new AttributedOverrideCatalog(new TypeCatalog(typeof(PluginA)));
catalog.SetMetadata("Priority", 5, typeof(PluginA));&lt;/PRE&gt;
&lt;H3&gt;How it works&lt;/H3&gt;
&lt;P&gt;The MetadataOverrideCatalog takes the part definitions from the wrapped catalog, and creates wrapper part definitions which return the overridden metadata but delegate all other functionality to the wrapped&amp;nbsp; part definition.&amp;nbsp; For an overview of what part definitions are, see my post on the &lt;A href="http://blogs.msdn.com/dsplaisted/archive/2009/06/08/a-crash-course-on-the-mef-primitives.aspx" mce_href="http://blogs.msdn.com/dsplaisted/archive/2009/06/08/a-crash-course-on-the-mef-primitives.aspx"&gt;MEF Primitives&lt;/A&gt;.&lt;/P&gt;
&lt;P&gt;The MetadataOverrideCatalog is an abstract class with one abstract method: GetExportMetadata, which takes a part and an export as parameters and returns the metadata that should be used for the export (or null if the default metadata should be used).&amp;nbsp; This lets derived catalogs define the specifics of how metadata should be overridden.&amp;nbsp; The AttributedOverrideCatalog provides an implementation which lets you override metadata by passing in the type that the export is defined on.&lt;/P&gt;
&lt;P&gt;This is just a sample—in general the hosting code won’t have a reference to the extension type, so you might want to write a catalog which determines what metadata to override based on a configuration file.&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/dsplaisted/attachment/9988573.ashx" mce_href="http://blogs.msdn.com/dsplaisted/attachment/9988573.ashx"&gt;Download the source code here&lt;/A&gt;.&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9988573" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>Podcast with Me on Testing on the MEF Team and at Microsoft</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2010/02/17/podcast-with-me-on-testing-on-the-mef-team-and-at-microsoft.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2010/02/17/podcast-with-me-on-testing-on-the-mef-team-and-at-microsoft.aspx</id><published>2010-02-17T01:52:17Z</published><updated>2010-02-17T01:52:17Z</updated><content type="html">&lt;p&gt;This week I was on the Herding Code podcast, discussing how we do testing on the MEF team and at Microsoft.&amp;#160; You can &lt;a href="http://herdingcode.com/?p=239"&gt;listen to it here&lt;/a&gt;.&lt;/p&gt;  &lt;p&gt;This was the first podcast I’ve been on and I enjoyed it quite a bit.&amp;#160; Some lessons learned:&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;When recording a podcast over Skype, make sure you have a good internet connection.&amp;#160; I was using a wireless internet service, and my audio quality is really poor.&amp;#160; I apologize for this and hope that most of what I say is still understandable.&lt;/li&gt;    &lt;li&gt;For a fun game, count the number of times I say “Ummm” and “Uh…” in the podcast!&lt;/li&gt;    &lt;li&gt;If, during an interview, you stop and make an aside that you expect to be edited out (such as “Man, you sure are going to have to edit out a lot of Ummms”), that part may not actually get edited out. :-)&lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;Many thanks to Jon Galloway and the rest of the Herding Code crew for having me on their podcast.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9964770" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>Import Cardinality, and Picking Which Export to Use</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2009/08/10/import-cardinality-and-picking-which-export-to-use.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2009/08/10/import-cardinality-and-picking-which-export-to-use.aspx</id><published>2009-08-11T00:16:03Z</published><updated>2009-08-11T00:16:03Z</updated><content type="html">&lt;p&gt;In the &lt;a href="http://mef.codeplex.com/"&gt;Managed Extensibility Framework&lt;/a&gt; (MEF), an import has a cardinality, which expresses how many exports can be used to satisfy the import.&amp;#160; The possible values are ZeroOrOne, ExactlyOne, or ZeroOrMore, and they can be declared in the following ways:&lt;/p&gt;  &lt;div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:812469c5-0cb0-4c63-8c15-c81123a09de7:4d0c2156-6ec7-4721-b9eb-6c15230198db" class="wlWriterEditableSmartContent"&gt;&lt;pre name="code" class="c#:nogutter:nocontrols"&gt;[Import(AllowDefault = true)]
IService ZeroOrOneImport { get; set; }

[Import]
IService ExactlyOneImport { get; set; }

//	Note that the property here is an array.
//	It could also be IEnumerable&amp;lt;IService&amp;gt; or a concrete type that implements ICollection&amp;lt;IService&amp;gt;.
[ImportMany]
IService[] ZeroOrMoreImport { get; set; }&lt;/pre&gt;&lt;/div&gt;

&lt;p&gt;If the cardinality of the import is ExactlyOne, then there must be exactly one matching export available.&amp;#160; If there are zero, or if there are two or more, then the import will not be satisfied, and the part will either be rejected or the composition will fail.&lt;/p&gt;

&lt;p&gt;A common question we get about MEF is how to modify this behavior, either by specifying a default export to use, or by specifying some logic that will pick the best one according to some criteria.&amp;#160; This question recently came up internally at Microsoft, and our architect Blake Stone gave a good explanation and overview of the options.&amp;#160; The rest of this post is based on what he said.&lt;/p&gt;

&lt;p&gt;In general, we strongly encourage consumer-side policy on picking one of many for what we believe is a good reason. We're trying to encourage not just individual stand-alone extensible systems, but the development of reusable subsystems. If two different teams develop something useful independently then we'd like to be able to drop both of them into a single product and have them work. Designing with a system-wide policy in mind prevents this from working. A natural workaround is to try to isolate the two subsystems from one another using different containers, but this also leads to problems down the road as subsystems tend to overlap in time - and it becomes awkward for one part to participate in more than one subsystem.&lt;/p&gt;

&lt;p&gt;So the recommended approaches look like this:&lt;/p&gt;

&lt;p&gt;a) Make the importer aware of the selection policy.&amp;#160; Change the import to an ImportMany (and the corresponding property to a collection), and have the importer choose which export to use from the list.&amp;#160; You can avoid duplicating the code to select the service to use in each importer by writing a custom collection class (which implements ICollection&amp;lt;T&amp;gt;), with an accessor for getting the desired T.&amp;#160; Then you can use [ImportMany(typeof(IService))] PolicyBased&amp;lt;IService&amp;gt; (where PolicyBased&amp;lt;T&amp;gt; is the custom collection you wrote) and let the reusable prioritization mechanism do the work for you. Many different schemes along these lines can co-exist.&lt;/p&gt;

&lt;p&gt;b) Use two different contracts. In this instance the importer can go ahead and write [Import] IService and pretend things are simple. An exporter, on the other hand would need to [Export(&amp;quot;my.namespace.PrioritizedService&amp;quot;)] and another part would import all of the prioritized services, pick one, and export it under the IService type-derived contract.&lt;/p&gt;

&lt;p&gt;It's worth keeping in mind that in both cases the selection mechanism is required to produce something meaningful, so you'd have to come up with a default IService implementation.&lt;/p&gt;

&lt;p&gt;c) If you really must make all of this transparent per your original request, yes that can also be achieved. Just keep in mind that you're opting out of widespread reuse of the functionality you write that depends on it. What you need to do is define your own custom topology of ExportProviders for a container. Implementing a full-fledged ExportProvider can be tricky, but implementing one as a filter over other full-fledged implementations is relatively straightforward. Our own AggregateExportProvider uses a prioritization scheme of its own along these lines (exporters found earlier in its list are preferred over ones found later for the purpose of satisfying imports of exactly one implementation.) For more information on how to do this, see Glenn Block’s blog post on &lt;a href="http://blogs.msdn.com/gblock/archive/2009/05/14/customizing-container-behavior-part-2-of-n-defaults.aspx"&gt;customizing container behavior with defaults&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9863519" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>A Crash Course on the MEF Primitives</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2009/06/08/a-crash-course-on-the-mef-primitives.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2009/06/08/a-crash-course-on-the-mef-primitives.aspx</id><published>2009-06-08T22:01:16Z</published><updated>2009-06-08T22:01:16Z</updated><content type="html">&lt;p&gt;With the &lt;a href="http://mef.codeplex.com/"&gt;Managed Extensibility Framework&lt;/a&gt; (MEF), you can use Import and Export attributes to declare what a class consumes and what it offers.&amp;#160; For example, below is an example of two different shapes and a toolbox that imports all available shapes.&lt;/p&gt;  &lt;pre class="brush: csharp; gutter: false;"&gt;[Export(typeof(Shape))]
public class Square : Shape
{
    //    Implementation
}

[Export(typeof(Shape))]
public class Circle : Shape
{
    //    Implementation
}

[Export]
public class Toolbox
{
    [ImportMany]
    public Shape[] Shapes { get; set; }

    //    Additional implementation...
}&lt;/pre&gt;

&lt;p&gt;Generally, to use these components, you will create a catalog which includes them, create a container hooked up to the catalog, and then request a root object from the container, like this:&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;var catalog = new AssemblyCatalog(typeof(Square).Assembly);
var container = new CompositionContainer(catalog);

Toolbox toolbox = container.GetExportedObject&amp;lt;Toolbox&amp;gt;();&lt;/pre&gt;

&lt;p&gt;When you request an item from the container, it finds it in the catalog, looks for any imports it has (and the imports of its imports, and so on), creates the objects and wires up the graph as specified by the imports and exports, and returns the object you requested.&lt;/p&gt;

&lt;h1&gt;&lt;/h1&gt;

&lt;h2&gt;The MEF Primitives&lt;/h2&gt;

&lt;p&gt;Based on the above summary, it may seem like a MEF catalog is simply a collection of types that the container can use.&amp;#160; However, catalogs actually provide the available components to the container through an abstraction layer which we call the primitives.&amp;#160; The primitives provide APIs for describing, creating, and using components.&lt;/p&gt;

&lt;p&gt;An implementation of the primitives specifies how components are defined, and is called a programming model.&amp;#160; Different catalogs can provide components that are defined using different programming models.&amp;#160; The default programming model for MEF is the attributed programming model which uses the Import and Export attributes.&amp;#160; The TypeCatalog, AssemblyCatalog, and DirectoryCatalog that ship with MEF use this programming model.&lt;/p&gt;

&lt;p&gt;The ability to use a different programming model provides a lot of flexibility.&amp;#160; Instead of using the Import and Export attributes, you could have your imports and exports defined based on a convention or an external configuration file.&amp;#160; You could also write a catalog where the components are defined using a dynamic language such as IronPython or IronRuby.&amp;#160; And you can use an AggregateCatalog to combine all of these catalogs and use them all together in the same container.&lt;/p&gt;

&lt;h2&gt;MEF Primitives Definitions&lt;/h2&gt;

&lt;p&gt;ComposablePartDefinition and ComposablePart are the MEF primitives classes which represent a component.&amp;#160; The relationship between a definition and a part is similar to the relationship between a type and an instance.&amp;#160; A part represents an instance of a component.&amp;#160; A part can be created from a part definition using the CreatePart() method.&amp;#160; In contrast to CLR types, however, a ComposablePart does not need to have a corresponding ComposablePartDefinition.&lt;/p&gt;

&lt;p&gt;The exports and imports of a part or part definition are represented by ExportDefinitions and ImportDefinitions:&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;public abstract IEnumerable&amp;lt;ExportDefinition&amp;gt; ExportDefinitions { get; }
public abstract IEnumerable&amp;lt;ImportDefinition&amp;gt; ImportDefinitions { get; }&lt;/pre&gt;

&lt;p&gt;An export definition has a ContractName property which specifies the contract which is being exported, and a Metadata property (which is a dictionary of string to object) which can store additional information about the export.&lt;/p&gt;

&lt;p&gt;An import definition specifies what exports can be used to satisfy the import.&amp;#160; It does this using a constraint, which is an expression that can be evaluated on an export definition to determine if a given export can satisfy the import.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;public virtual Expression&amp;lt;Func&amp;lt;ExportDefinition, bool&amp;gt;&amp;gt; Constraint { get; }&lt;/pre&gt;

&lt;p&gt;Nicholas Blumhardt has written a blog post about the &lt;a href="http://blogs.msdn.com/nblumhardt/archive/2009/04/16/mef-dependencies-are-queries.aspx"&gt;import being represented as a constraint&lt;/a&gt; which covers this in more depth.&amp;#160; The import definition also has properties which specify whether the import supports &lt;a href="http://mef.codeplex.com/Wiki/View.aspx?title=Recomposition"&gt;recomposition&lt;/a&gt; and its cardinality.&amp;#160; The cardinality specifies how many exports can be used to satisfy the import, and can be ZeroOrMore (for collection imports), ExactlyOne (for required single-valued imports), or ZeroOrOne (for optional single-valued imports).&lt;/p&gt;

&lt;h2&gt;ComposablePart&lt;/h2&gt;

&lt;p&gt;In addition to the export and import definitions, a composable part provides functionality for setting the part’s imports and getting its exports.&lt;/p&gt;

&lt;pre class="brush: csharp; gutter: false;"&gt;public abstract void SetImport(ImportDefinition definition, IEnumerable&amp;lt;Export&amp;gt; exports);
public virtual void OnComposed();
public abstract object GetExportedValue(ExportDefinition definition);&lt;/pre&gt;

&lt;p&gt;SetImport is used to set the imports for a part.&amp;#160; The first argument is the import definition of the import to set, and the second argument is a list of exports to satisfy the import.&amp;#160; The Export class used here contains the same contract name and metadata information that an export definition would have, but it also has a GetExportedValue() method to return the actual value of the export.&lt;/p&gt;

&lt;p&gt;OnComposed will be called after all of the imports have been satisfied.&amp;#160; After that, GetExportedValue may be called to get the exported value for an export (specified by the ExportDefinition).&amp;#160; If any imports are recomposable, SetImport and then OnComposed will be called again if the available imports change.&lt;/p&gt;

&lt;h2&gt;Custom Catalogs and Custom ExportProviders&lt;/h2&gt;

&lt;p&gt;To create a custom programming model, create your own part definition and part classes which derive from ComposablePartDefinition and ComposablePart.&amp;#160; You may also need to create your own implementations of ImportDefinition and ExportDefinition.&amp;#160; Then create a catalog class which derives from ComposablePartCatalog, and override the Parts property to return a collection of your custom part definitions.&lt;/p&gt;

&lt;p&gt;Writing a programming model from scratch can be quite complex.&amp;#160; If you want a programming model similar to the default MEF model, but where the imports and exports are defined in different ways (such as through convention or configuration), you may be able to use the methods in the static ReflectionModelServices and AttributedModelServices classes to simplify this.&lt;/p&gt;

&lt;p&gt;If you simply want to provide exports to the MEF container, but the exports don’t correspond to parts that have any imports that need to be satisfied by MEF, you can simply implement a custom ExportProvider.&amp;#160; This might be useful if you want services from an existing service locater to be available to MEF parts, or if you want to supply configuration values stored in a file.&lt;/p&gt;

&lt;h2&gt;Further Information&lt;/h2&gt;

&lt;p&gt;For more information on MEF and the primitives, see the &lt;a href="http://mef.codeplex.com/"&gt;MEF CodePlex site&lt;/a&gt;.&amp;#160; In particular you may want to read the &lt;a href="http://mef.codeplex.com/Wiki/View.aspx?title=Architecture"&gt;Architecture Overview&lt;/a&gt; and the &lt;a href="http://mef.codeplex.com/Project/Download/FileDownload.aspx?DownloadId=62133"&gt;Hosting the .NET Composition Primitives whitepaper&lt;/a&gt;.&amp;#160; And of course feel free to ask questions on the &lt;a href="http://mef.codeplex.com/Thread/List.aspx"&gt;MEF Forums&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9709140" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>MEFGrid: A Sample MEF Application</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2009/01/14/mefgrid-a-sample-mef-application.aspx" /><link rel="enclosure" type="application/x-zip-compressed" length="119941" href="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-31-94-84/MEFGrid.zip" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2009/01/14/mefgrid-a-sample-mef-application.aspx</id><published>2009-01-15T00:48:00Z</published><updated>2009-01-15T00:48:00Z</updated><content type="html">&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/dsplaisted/WindowsLiveWriter/MEFGridASampleMEFApplication_10CD5/image_4.png" mce_href="http://blogs.msdn.com/blogfiles/dsplaisted/WindowsLiveWriter/MEFGridASampleMEFApplication_10CD5/image_4.png"&gt;&lt;IMG title=image style="BORDER-TOP-WIDTH: 0px; DISPLAY: inline; BORDER-LEFT-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-RIGHT-WIDTH: 0px" height=484 alt=image src="http://blogs.msdn.com/blogfiles/dsplaisted/WindowsLiveWriter/MEFGridASampleMEFApplication_10CD5/image_thumb_1.png" width=644 border=0 mce_src="http://blogs.msdn.com/blogfiles/dsplaisted/WindowsLiveWriter/MEFGridASampleMEFApplication_10CD5/image_thumb_1.png"&gt;&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;MEFGrid is a sample &lt;A title="Managed Extensibility Framework Codeplex Site" href="http://codeplex.com/mef" mce_href="http://codeplex.com/mef"&gt;MEF&lt;/A&gt; application that I presented at Seattle Code Camp and at an Olympia .NET user group meeting.&amp;nbsp; It includes connect 4 and the game of life, but other grid based games could be written and dropped into the extensions directory.&lt;/P&gt;
&lt;P&gt;The application demonstrates some of the more advanced features of MEF.&amp;nbsp; The available life patterns, for example, are stored as text files in the LifePatterns directory.&amp;nbsp; A custom catalog makes these available as string-based exports via a custom programming model, and the life game uses a contract adapter to convert the string-based exports to command exports that set the current life pattern.&lt;/P&gt;
&lt;P&gt;If I can find the time I will write a series of blog posts explaining how the application works in more detail.&amp;nbsp; For now, feel free to post questions in the comments or on the &lt;A href="http://www.codeplex.com/MEF/Thread/List.aspx" mce_href="http://www.codeplex.com/MEF/Thread/List.aspx"&gt;MEF discussion forums&lt;/A&gt;.&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/dsplaisted/attachment/9319484.ashx" mce_href="http://blogs.msdn.com/dsplaisted/attachment/9319484.ashx"&gt;Download the MEFGrid sample&lt;/A&gt;.&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9319484" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry><entry><title>Session on MEF at Seattle Code Camp this Sunday</title><link rel="alternate" type="text/html" href="http://blogs.msdn.com/b/dsplaisted/archive/2008/11/13/session-on-mef-at-seattle-code-camp-this-sunday.aspx" /><id>http://blogs.msdn.com/b/dsplaisted/archive/2008/11/13/session-on-mef-at-seattle-code-camp-this-sunday.aspx</id><published>2008-11-14T00:56:59Z</published><updated>2008-11-14T00:56:59Z</updated><content type="html">&lt;p&gt;I am giving a session on the Managed Extensibility Framework (MEF) this Sunday at &lt;a href="https://seattle.codecamp.us/default.aspx"&gt;Seattle Code Camp&lt;/a&gt;.&amp;nbsp; I will be demoing how to build an extensible application using MEF.&amp;nbsp; It will be fun (I hope), heavily code-focused, and will cover most of the core features of MEF.&lt;/p&gt; &lt;p&gt;MEF was featured in the PDC keynote, and for a quick introduction to MEF, you can watch that part of the keynote &lt;a title="PDC 2008 Keynote MEF Demo" href="http://blogs.msdn.com/brada/archive/2008/11/07/managed-extensibility-framework-mef-demo.aspx"&gt;here&lt;/a&gt;.&lt;/p&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9067595" width="1" height="1"&gt;</content><author><name>dsplaisted</name><uri>http://blogs.msdn.com/dsplaisted/ProfileUrlRedirect.ashx</uri></author></entry></feed>