<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="http://blogs.msdn.com/utility/FeedStylesheets/rss.xsl" media="screen"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/"><channel><title>Daniel Plaisted's Blog</title><link>http://blogs.msdn.com/b/dsplaisted/</link><description /><dc:language>en-US</dc:language><generator>Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><item><title>How To Control Who Can Write Extensions For Your MEF Application</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2010/11/01/how-to-control-who-can-write-extensions-for-your-mef-application.aspx</link><pubDate>Mon, 01 Nov 2010 23:28:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10084406</guid><dc:creator>dsplaisted</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=10084406</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2010/11/01/how-to-control-who-can-write-extensions-for-your-mef-application.aspx#comments</comments><description>&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;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-08-44-06/StrongNameCatalog.zip" length="19662" type="application/x-zip-compressed" /></item><item><title>How to Debug and Diagnose MEF Failures</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx</link><pubDate>Tue, 13 Jul 2010 21:10:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10037790</guid><dc:creator>dsplaisted</dc:creator><slash:comments>9</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=10037790</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2010/07/13/how-to-debug-and-diagnose-mef-failures.aspx#comments</comments><description>&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;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-10-03-77-90/Composition.Diagnostics.zip" length="100707" type="application/x-zip-compressed" /></item><item><title>Presentation at TechEd North America 2010</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2010/05/27/presentation-at-teched-north-america-2010.aspx</link><pubDate>Thu, 27 May 2010 00:22:49 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10016005</guid><dc:creator>dsplaisted</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=10016005</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2010/05/27/presentation-at-teched-north-america-2010.aspx#comments</comments><description>&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;</description></item><item><title>Overriding MEF Metadata</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2010/04/01/overriding-mef-metadata.aspx</link><pubDate>Thu, 01 Apr 2010 04:49:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9988573</guid><dc:creator>dsplaisted</dc:creator><slash:comments>2</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=9988573</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2010/04/01/overriding-mef-metadata.aspx#comments</comments><description>&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;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-98-85-73/MetadataOverride.zip" length="19385" type="application/x-zip-compressed" /></item><item><title>Podcast with Me on Testing on the MEF Team and at Microsoft</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2010/02/17/podcast-with-me-on-testing-on-the-mef-team-and-at-microsoft.aspx</link><pubDate>Wed, 17 Feb 2010 01:52:17 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9964770</guid><dc:creator>dsplaisted</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=9964770</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2010/02/17/podcast-with-me-on-testing-on-the-mef-team-and-at-microsoft.aspx#comments</comments><description>&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;</description></item><item><title>Import Cardinality, and Picking Which Export to Use</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2009/08/10/import-cardinality-and-picking-which-export-to-use.aspx</link><pubDate>Tue, 11 Aug 2009 00:16:03 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9863519</guid><dc:creator>dsplaisted</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=9863519</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2009/08/10/import-cardinality-and-picking-which-export-to-use.aspx#comments</comments><description>&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;</description></item><item><title>A Crash Course on the MEF Primitives</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2009/06/08/a-crash-course-on-the-mef-primitives.aspx</link><pubDate>Mon, 08 Jun 2009 22:01:16 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9709140</guid><dc:creator>dsplaisted</dc:creator><slash:comments>3</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=9709140</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2009/06/08/a-crash-course-on-the-mef-primitives.aspx#comments</comments><description>&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;</description></item><item><title>MEFGrid: A Sample MEF Application</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2009/01/14/mefgrid-a-sample-mef-application.aspx</link><pubDate>Thu, 15 Jan 2009 00:48:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9319484</guid><dc:creator>dsplaisted</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=9319484</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2009/01/14/mefgrid-a-sample-mef-application.aspx#comments</comments><description>&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;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-31-94-84/MEFGrid.zip" length="119941" type="application/x-zip-compressed" /></item><item><title>Session on MEF at Seattle Code Camp this Sunday</title><link>http://blogs.msdn.com/b/dsplaisted/archive/2008/11/13/session-on-mef-at-seattle-code-camp-this-sunday.aspx</link><pubDate>Fri, 14 Nov 2008 00:56:59 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9067595</guid><dc:creator>dsplaisted</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/dsplaisted/rsscomments.aspx?WeblogPostID=9067595</wfw:commentRss><comments>http://blogs.msdn.com/b/dsplaisted/archive/2008/11/13/session-on-mef-at-seattle-code-camp-this-sunday.aspx#comments</comments><description>&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;</description></item></channel></rss>
