<?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>MEF and more</title><link>http://blogs.msdn.com/b/hammett/</link><description /><dc:language>en-US</dc:language><generator>Telligent Evolution Platform Developer Build (Build: 5.6.50428.7875)</generator><item><title>MEF’s Convention model</title><link>http://blogs.msdn.com/b/hammett/archive/2011/03/08/mef-s-convention-model.aspx</link><pubDate>Wed, 09 Mar 2011 02:51:28 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10138440</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>14</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=10138440</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2011/03/08/mef-s-convention-model.aspx#comments</comments><description>&lt;p&gt;In the last drop of MEF on codeplex we introduced a handful of interesting features. One of them – which has a large API surface – is the new registration mechanism. It allows you to accomplish interesting things:&lt;/p&gt; &lt;ul&gt;&lt;li&gt;Define a predicate (rule) that will cause all matching types to be exported as MEF parts  &lt;/li&gt;&lt;li&gt;Export types that you do not have access to the source code  &lt;/li&gt;&lt;li&gt;Bridge an existing plugin model – say, FxCop’s – to MEF’s API &lt;/li&gt; &lt;/ul&gt;&lt;p&gt;Using it is quite simple. Suppose you have the following types in a project:&lt;/p&gt;&lt;pre class="csharpcode"&gt;    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;interface&lt;/span&gt; IController
    {
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; AccountController : IController
    {
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; HomeController : IController
    {
    }&lt;/pre&gt;
&lt;p&gt;

&lt;/p&gt;
&lt;p&gt;You can then decide the export AccountController and HomeController based on something they share: they both implement IController. (Additionally, they both are concrete classes whose type name ends with ‘Controller’, and you could also define a rule based on this). &lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; System;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.ComponentModel.Composition;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.ComponentModel.Composition.Hosting;
&lt;span class="kwrd"&gt;using&lt;/span&gt; System.ComponentModel.Composition.Registration;

&lt;span class="kwrd"&gt;class&lt;/span&gt; Program
{
    &lt;span class="kwrd"&gt;static&lt;/span&gt; &lt;span class="kwrd"&gt;void&lt;/span&gt; Main(&lt;span class="kwrd"&gt;string&lt;/span&gt;[] args)
    {
        var registration = &lt;span class="kwrd"&gt;new&lt;/span&gt; RegistrationBuilder();

        registration.Implements&amp;lt;IController&amp;gt;().
            Export&amp;lt;IController&amp;gt;();

        var catalog = &lt;span class="kwrd"&gt;new&lt;/span&gt; AssemblyCatalog(
            &lt;span class="kwrd"&gt;typeof&lt;/span&gt;(Program).Assembly, registration);
        var container = &lt;span class="kwrd"&gt;new&lt;/span&gt; CompositionContainer(catalog);
    }
}&lt;/pre&gt;
&lt;p&gt;

&lt;/p&gt;
&lt;p&gt;So we build a RegistrationBuilder and tell it to get all types that implement IController, and export those types with the IController contract. &lt;/p&gt;
&lt;p&gt;&lt;font color="#ff0000"&gt;Note though, that the RegistrationBuilder is _not_ a catalog. It is passed to a catalog – in the example above, an AssemblyCatalog. So the universe of types applicable to this RegistrationBuilder is limited to the set of types that this AssemblyCatalog can “discover”.&lt;/font&gt;&lt;/p&gt;
&lt;p&gt;If you’re unsure it’s working, you can set a breakpoint in your code and investigate the Parts property of the catalog. It should have two “Parts”: HomeController and AccountController, both exporting a single contract: IController.&lt;/p&gt;
&lt;h2&gt;&lt;/h2&gt;
&lt;h2&gt;Exporting Self&lt;/h2&gt;
&lt;p&gt;We could make a small change to have them exporting more than the IController contract. &lt;/p&gt;&lt;pre class="csharpcode"&gt;        registration.Implements&amp;lt;IController&amp;gt;().
            &lt;strong&gt;Export().&lt;/strong&gt;
            Export&amp;lt;IController&amp;gt;();
&lt;/pre&gt;


&lt;p&gt;The single .Export will cause the type to be exported as “itself”. It’s the equivalent of just adding a [Export] attribute to a type, whereas the other line – Export&amp;lt;IController&amp;gt; – is the equivalent of [Export(typeof(IController))]&lt;/p&gt;
&lt;h2&gt;Configuring the export&lt;/h2&gt;
&lt;p&gt;You’d also notice that some of the API takes an optional configuration instance wrapped in an Action delegate. Export() takes ExportBuilder. Import() takes ImportBuilders. You can use it to add more stuff to the Export/Import such as metadata. &lt;/p&gt;&lt;pre class="csharpcode"&gt;            registration.Implements&amp;lt;IController&amp;gt;().
                Export(config =&amp;gt; config.AddMetadata(&lt;span class="str"&gt;"name"&lt;/span&gt;, t =&amp;gt; t.Name)).
                Export&amp;lt;IController&amp;gt;();&lt;/pre&gt;&lt;pre class="csharpcode"&gt;&amp;nbsp;&lt;/pre&gt;


&lt;h2&gt;Where’s the convention?&lt;/h2&gt;
&lt;p&gt;Interesting question. Our piece of code will select all types matching the predicate (in this case, Implements&amp;lt;&amp;gt; is a shortcut to a predicate). We don’t know how many will match: 1, 2, 100 controllers? Who knows?&lt;/p&gt;
&lt;p&gt;It’s not reasonable to think that all these controllers would look the same. First and foremost, some are bound to use constructors. What should you do? &lt;/p&gt;
&lt;p&gt;Well, nothing. By &lt;strong&gt;convention&lt;/strong&gt; our RegistrationBuilder will select the constructor with most parameters. Also, if something looks like a collection, it will change the import cardinality to Zero or Many – which is the equivalent of using the [ImportMany] attribute. &lt;/p&gt;
&lt;p&gt;Sweet, isn’t it?&lt;/p&gt;
&lt;h2&gt;Bypassing the convention&lt;/h2&gt;
&lt;p&gt;What if? What if you want to use a different constructor for a specific controller? What if a controller happens to have two constructors with the same number of arguments?&lt;/p&gt;
&lt;p&gt;In this case, reject the convention by being explicit. Suppose your AccontController looks like the following:&lt;/p&gt;&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; AccountController : IController
{
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IMembershipProvider _provider;
    &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IAuthentication _auth;

    &lt;span class="kwrd"&gt;public&lt;/span&gt; AccountController(IMembershipProvider provider)
    {
        _provider = provider;
    }

    &lt;span class="kwrd"&gt;public&lt;/span&gt; AccountController(IAuthentication auth)
    {
        _auth = auth;
    }
}&lt;/pre&gt;

In this case, add the following registration code specifically to the AccountController. Notice that it selects the constructor based on a Expression&amp;lt;&amp;gt;. We thought this is great as it’s refactor-friendly. &lt;pre class="csharpcode"&gt;    registration.OfType&amp;lt;AccountController&amp;gt;()
        .SelectConstructor(builder =&amp;gt; 
            &lt;span class="kwrd"&gt;new&lt;/span&gt; AccountController(
                builder.Import&amp;lt;IMembershipProvider&amp;gt;()));
&lt;/pre&gt;


&lt;p&gt;The first parameter your lambda takes is a ParameterImportBuilder. Its Import methods allows you to further configure the import as well..&lt;/p&gt;
&lt;h2&gt;Explicit wiring&lt;/h2&gt;
&lt;p&gt;This is a recurring question: “I have two Foo’s. My piece of code imports just one. Mef blows up. What should I do?”&lt;/p&gt;
&lt;p&gt;MEF rightfully throws an exception in this case, since it cannot tell which Foo it should give to the importer of a single one. But what to do about it? Well, building on our last example, imagine that AccountController takes a single IAuthentication instance, but you have two available: &lt;/p&gt;&lt;pre class="csharpcode"&gt;
    registration.OfType&amp;lt;DummyAuth1&amp;gt;()
        .Export&amp;lt;IAuthentication&amp;gt;();
            
    registration.OfType&amp;lt;DummyAuth2&amp;gt;()
        .Export&amp;lt;IAuthentication&amp;gt;();
        
    ...
    
    &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; AccountController : IController
    {
        &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;readonly&lt;/span&gt; IAuthentication _auth;

        &lt;span class="kwrd"&gt;public&lt;/span&gt; AccountController(IAuthentication auth)
        {
            _auth = auth;
        }
    }&lt;/pre&gt;


&lt;p&gt;Our solution to this problem is to “name” an specific export and then use this “name” on the import side as well.&lt;/p&gt;&lt;pre class="csharpcode"&gt;
    registration.OfType&amp;lt;DummyAuth1&amp;gt;()
        .Export&amp;lt;IAuthentication&amp;gt;(
           builder =&amp;gt; &lt;strong&gt;builder.Named(&lt;span class="str"&gt;"my_1"&lt;/span&gt;)&lt;/strong&gt;);
            
    registration.OfType&amp;lt;DummyAuth2&amp;gt;()
        .Export&amp;lt;IAuthentication&amp;gt;();

    registration.OfType&amp;lt;AccountController&amp;gt;()
        .SelectConstructor(builder =&amp;gt; 
            &lt;span class="kwrd"&gt;new&lt;/span&gt; AccountController(
                builder.Import&amp;lt;IAuthentication&amp;gt;(
                    config =&amp;gt; &lt;strong&gt;config.Named(&lt;span class="str"&gt;"my_1"&lt;/span&gt;)&lt;/strong&gt;)));
&lt;/pre&gt;


&lt;p&gt;&amp;nbsp;&lt;/p&gt;
&lt;p&gt;This was a quick overview of this feature. There’s more to come, let me know what you’d think. &lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10138440" width="1" height="1"&gt;</description></item><item><title>MEF Gems 2 of many: Collections</title><link>http://blogs.msdn.com/b/hammett/archive/2010/10/28/mef-gems-2-of-many-collections.aspx</link><pubDate>Thu, 28 Oct 2010 21:27:22 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10082453</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=10082453</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2010/10/28/mef-gems-2-of-many-collections.aspx#comments</comments><description>&lt;p&gt;So in the &lt;a href="http://blogs.msdn.com/b/hammett/archive/2010/09/27/mef-gems-1-of-many-import-vs-importmany.aspx"&gt;previous gem&lt;/a&gt; I went over the differences between import and import many. Now let’s consider the different ways to import many dependencies. &lt;/p&gt;  &lt;p&gt;Check this piece of code:&lt;/p&gt;  &lt;pre class="csharpcode"&gt;    [InheritedExport]
    &lt;span class="kwrd"&gt;abstract&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Foo { }

    &lt;span class="kwrd"&gt;class&lt;/span&gt; Foo1 : Foo { }
    &lt;span class="kwrd"&gt;class&lt;/span&gt; Foo2 : Foo { }
    &lt;span class="kwrd"&gt;class&lt;/span&gt; Foo3 : Foo { }&lt;/pre&gt;


&lt;p&gt;So here we have a single contract and three exports just to make volume and test the collection imports. The first way you’d think of importing them would be using IEnumerable&amp;lt;Foo&amp;gt;:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    [Export]
    &lt;span class="kwrd"&gt;class&lt;/span&gt; ImportsOfCollections
    {
        [ImportMany]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; IEnumerable&amp;lt;Foo&amp;gt; Foos { get; set; }
    }&lt;/pre&gt;

&lt;p&gt;And this works. Note that MEF will instantiate an implementation of IEnumerable&amp;lt;T&amp;gt; and set the property. This is the default behavior for this type. &lt;/p&gt;

&lt;p&gt;Another way you may consider is a standard array:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;    [Export]
    &lt;span class="kwrd"&gt;class&lt;/span&gt; ImportsOfCollections
    {
        [ImportMany]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; Foo[] FoosArray { get; set; }
    }&lt;/pre&gt;


&lt;p&gt;This option also leaves to MEF the instantiation of the array type. &lt;/p&gt;

&lt;p&gt;Now, a different way would be using ICollection&amp;lt;T&amp;gt;: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;    [Export]
    &lt;span class="kwrd"&gt;class&lt;/span&gt; ImportsOfCollections
    {
        [ImportMany]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; ICollection&amp;lt;Foo&amp;gt; FoosColl { get; set; }
    }&lt;/pre&gt;

&lt;p&gt;In this case, if you run this code &lt;font style="background-color: #ffff00"&gt;you’ll get an error&lt;/font&gt;. That’s because MEF doesn’t know which implementation of ICollection you want. It expects you to take care of that. &lt;u&gt;Easy fix&lt;/u&gt;: &lt;/p&gt;

&lt;pre class="csharpcode"&gt;    [Export]
    &lt;span class="kwrd"&gt;class&lt;/span&gt; ImportsOfCollections
    {
        &lt;span class="kwrd"&gt;public&lt;/span&gt; ImportsOfCollections()
        {
            &lt;font style="background-color: #ffff00"&gt;FoosColl = &lt;span class="kwrd"&gt;new&lt;/span&gt; List&amp;lt;Foo&amp;gt;();&lt;/font&gt;
        }

        [ImportMany]
        &lt;span class="kwrd"&gt;public&lt;/span&gt; ICollection&amp;lt;Foo&amp;gt; FoosColl { get; set; }
    }&lt;/pre&gt;


&lt;p&gt;And now it will work as expected. This allows you to use anything that implements ICollection&amp;lt;T&amp;gt; including ObservableCollection&amp;lt;T&amp;gt;.&lt;/p&gt;

&lt;h2&gt;Behavior on recomposition&lt;/h2&gt;

&lt;p&gt;What would happen to my collections if a recomposition is triggered? It depends.&lt;/p&gt;

&lt;p&gt;If MEF owns the collection instance, it would supply your components with new instances. Otherwise, it will call .Clear and .Add as many time as needed to repopulate the collection. &lt;/p&gt;

&lt;p&gt;In other words, for IEnumerable&amp;lt;&amp;gt; and Array, MEF will supply a new instance to the property. For ICollection&amp;lt;&amp;gt; implementations, it will call .Clear and .Add.&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10082453" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/hammett/archive/tags/MEF/">MEF</category></item><item><title>MEF Gems–1 of many: Import vs ImportMany</title><link>http://blogs.msdn.com/b/hammett/archive/2010/09/27/mef-gems-1-of-many-import-vs-importmany.aspx</link><pubDate>Mon, 27 Sep 2010 22:35:25 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10068429</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=10068429</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2010/09/27/mef-gems-1-of-many-import-vs-importmany.aspx#comments</comments><description>&lt;p&gt;Phew! We’ve been working hard! I’m planning to put another Codeplex drop soon so you can see and test the changes, and of course, share your feedback. Also looking forward to run a usability test – let me know if you’re in seattle/redmond area and if you’re willing to participate! &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-winkingsmile" alt="Winking smile" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-09-38-metablogapi/2352.wlEmoticonwinkingsmile_5F00_753BB855.png" /&gt;&lt;/p&gt;  &lt;p&gt;If you’ve been using MEF for a while you have stumbled upon [ImportMany] and are probably using it often. What you probably don’t know is the complete story on how MEF handles collections. &lt;/p&gt;  &lt;p&gt;&lt;strong&gt;What’s the difference between Import and ImportMany?&lt;/strong&gt;&lt;/p&gt;  &lt;p&gt;Underneath, MEF translates everything into ImportDefinition and ExportDefinition. ImportDefinition carries a cardinality: “zero or one”, “exactly one” or “zero or more”. When using the Import attribute you can either define zero or one or exactly one, which leaves one out. &lt;/p&gt;  &lt;p&gt;Consider the following:&lt;/p&gt;  &lt;p&gt;   &lt;pre class="csharpcode"&gt;[Export] Plane : ITransportSystem

[Export] Car : ITransportSystem

[ImportMany] IEnumerable&amp;lt;ITransportSystem&amp;gt;&lt;/pre&gt;
  You can safely guess what you will get, right? &lt;/p&gt;

&lt;p&gt;&amp;#160;&lt;/p&gt;

&lt;p&gt;The following is also interesting:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[Export] IEnumerable&amp;lt;ITransportSystem&amp;gt;

[Import] IEnumerable&amp;lt;ITransportSystem&amp;gt;&lt;/pre&gt;


&lt;p&gt;Some people ask for an aggregation:&lt;/p&gt;

&lt;pre class="csharpcode"&gt;[Export] Plane : ITransportSystem

[Export] Car : ITransportSystem

[ExportMany] IEnumerable&amp;lt;ITransportSystem&amp;gt;

&lt;span class="rem"&gt;// (Plane + Car + AllItems from previous one)&lt;/span&gt;
[ImportMany] IEnumerable&amp;lt;ITransportSystem&amp;gt; &lt;/pre&gt;

&lt;p&gt;But we don’t support this one…&lt;/p&gt;

&lt;p&gt;So ImportMany is a way to express that you want to import all “items” into a type capable of exposing many items (usually IEnumerable).. Next one I’ll explain more about this purposely vague last statement &lt;img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="http://blogs.msdn.com/cfs-file.ashx/__key/CommunityServer-Blogs-Components-WeblogFiles/00-00-01-09-38-metablogapi/1321.wlEmoticonsmile_5F00_628DA668.png" /&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10068429" width="1" height="1"&gt;</description></item><item><title>Container hierarchies in MEF: shaping it for the future (maybe)</title><link>http://blogs.msdn.com/b/hammett/archive/2010/09/09/container-hierarchies-in-mef-shaping-it-for-the-future-maybe.aspx</link><pubDate>Thu, 09 Sep 2010 22:42:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10060048</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>6</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=10060048</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2010/09/09/container-hierarchies-in-mef-shaping-it-for-the-future-maybe.aspx#comments</comments><description>&lt;p class="MsoNormal"&gt;Recapping: MEF supports two creation policies: shared (think
singleton) or non-shared (think transient, prototype or a fancy new operator).
MEF also recognizes types that implement IDisposable and correctly &amp;ldquo;implement
the protocol&amp;rdquo; for calling Dispose on them in the right time. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;This is all goodness, but as applications grow in complexity,
this is hardly enough. You can imagine a MDI application that wants distinct
singleton instances for each document. That&amp;rsquo;s actually why we decided to use
the name Shared instead of Singleton. A component is shared within a context.
Another historical fact is that in the early days, MEF&amp;rsquo;s container used to be
called CompositionDomain. Thinking about, I believe it was the perfect name:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;span style="font-family: Symbol;"&gt;&lt;span&gt;&lt;span style="font: 7pt 'Times New Roman';"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Each &amp;ldquo;domain&amp;rdquo; represents an isolated island of
components and their wirings (composition)&lt;/li&gt;
&lt;li&gt;&lt;span style="font-family: Symbol;"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;Each &amp;ldquo;domain&amp;rdquo; holds ownership of components it
instantiates&lt;/li&gt;
&lt;li&gt;&lt;span style="font-family: Symbol;"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;Each &amp;ldquo;domain&amp;rdquo; reclaim resources off what it owns
once it is disposed&lt;/li&gt;
&lt;li&gt;Optionally, a &amp;ldquo;domain&amp;rdquo; can be linked to a parent
domain, so dependencies can be fulfilled by components owned by the parent &lt;/li&gt;
&lt;/ul&gt;
&lt;p class="MsoNormal"&gt;The last bullet leads to an important compromise:&lt;span style="text-decoration: underline;"&gt; hierarchy
must be established in a way that the depth means shorter lifetime&lt;/span&gt;. In other
words, the top level container must be the one that lives the longest, and the
bottom container the one that lives the shortest. If you change this, hell
breaks loose.&lt;/p&gt;
&lt;p class="MsoNormal"&gt;For some reason the class was renamed (before I joined the
team) to CompositionContainer, but the principles remain. They allow you to
support requirements such as the typical &amp;ldquo;a container per-web-request&amp;rdquo; or &amp;ldquo;multi-tenancy&amp;rdquo;
where each container represents customizations for each tenant, and finally MDI
apps where each document means a new container; to name just a few. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;To surprise some of you, we have always supported containers
hierarchy in MEF. The API were always there:&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var parent = new
CompositionContainer(catalog);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var child = new
CompositionContainer(parent);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Unfortunately, the above doesn&amp;rsquo;t accomplish much. The only
way for MEF to discover components is through catalogs. So in order to control
what each container will own you have to manage the catalogs accordingly, and specify
the right ones when creating containers:&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var parent = new
CompositionContainer(&lt;b&gt;globalCatalog&lt;/b&gt;);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var child = new
CompositionContainer(&lt;b&gt;childCatalog&lt;/b&gt;,
parent);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;But the vast majority of applications start with a single
catalog, say DirectoryCatalog. What to do in this case?&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Aware of this, I published a &lt;a target="_blank" href="http://mef.codeplex.com/wikipage?title=Filtering%20Catalogs&amp;amp;referringTitle=Guide"&gt;FilteredCatalog&lt;/a&gt; sample code on
Codeplex. While it helps, it is still hard to get filtering right. &lt;/p&gt;
&lt;h2&gt;&lt;br /&gt;&lt;/h2&gt;
&lt;h2&gt;The problem in practice&lt;/h2&gt;
&lt;p class="MsoNormal"&gt;For the next release we are considering several options to
free &amp;ndash; or at least diminish &amp;ndash; the pain for users of MEF who need container
hierarchies in order to get &amp;ldquo;scoping&amp;rdquo;. As most of the pain is based on how to
deal with catalogs, we are currently focused on those. Note that this is a hard
problem and we may reject all options and table this for yet another release.
:-\&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Say you&amp;rsquo;re writing a MVC app using MEF. You also want
controllers and related artifacts to be isolated in a per-web-request basis. Your
starting point is a catalog that has everything plus the kitchen sink. You need
to select only the components that should be in the request level container.
How would you do it?&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span&gt;&lt;span&gt;&lt;span style="font: 7pt 'Times New Roman';"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Components (parts in the MEF lingo) have exports
&amp;ndash; remember the [Export]?&lt;/li&gt;
&lt;li&gt;&lt;span&gt;&lt;span&gt;&lt;span style="font: 7pt 'Times New Roman';"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Each controller is likely to export IController&lt;/li&gt;
&lt;li&gt;&lt;span&gt;&lt;span&gt;&lt;span style="font: 7pt 'Times New Roman';"&gt;&lt;/span&gt;&lt;/span&gt;&lt;/span&gt;Nailed it!&lt;/li&gt;
&lt;/ol&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var catalog = new
DirectoryCatalog(binFolder);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var perRequestCatalog =
catalog.Where( component -&amp;gt; component.Exports&amp;lt;IController&amp;gt;() );&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;This looks sufficient, right? The perRequestCatalog contains
all components that happen to export IController. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;What to do next? So far you have two pieces of information
in the form of sets: the catalog, which is a DirectoryCatalog and contains
everything (including the controllers) and a perRequestCatalog which contains
all controllers. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;Your gut reaction may be to write the following:&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var catalog = new
DirectoryCatalog(binFolder);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var perRequestCatalog =
catalog.Where( component -&amp;gt; component.Exports&amp;lt;IController&amp;gt;() );&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var parent = new
CompositionContainer(catalog);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;...&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var perRequestContainer =
new CompositionContainer(perRequestCatalog, parent);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Looks reasonable, right? Except that it&amp;rsquo;s wrong wrong wrong&amp;hellip;
Now the parent container points to a catalog that has everything, and the
perRequestContainer has just the catalogs. If you ask the latter for all
controllers, guess what will you get? All controllers. Twice. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;To fix that the parent container should point to a catalog
that has everything BUT the controllers. So this is a general rule for scoping
in MEF, you usually won&amp;rsquo;t want overlapping sets unless you know what you&amp;rsquo;re
doing. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;Going back to code, imagine we could write the following:&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var catalog = new
DirectoryCatalog(binFolder);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var catalogPair =
catalog.Where( component -&amp;gt; component.Exports&amp;lt;IController&amp;gt;() );&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;&amp;nbsp;&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var perRequestCatalog =
catalogPair.Matching;&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var appLevelCatalog =
catalogPair.Unmatching;&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Now the .Where call returned two sets: the true and the
false. The false set happens to be the input set minus the true set, aka the
difference, aka the complement. With that it&amp;rsquo;s easy to get it right: &lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var parent = new
CompositionContainer(appLevelCatalog);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;...&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;var perRequestContainer =
new CompositionContainer(perRequestCatalog, parent);&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&lt;span style="font-family: Consolas;"&gt;&lt;br /&gt;&lt;/span&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Now you will get the expected behavior, since the sets do
not overlap. &lt;/p&gt;
&lt;h1&gt;&lt;br /&gt;&lt;/h1&gt;
&lt;h1&gt;Shaping it&lt;/h1&gt;
&lt;p class="MsoNormal"&gt;Then it comes to how to expose it. We&amp;rsquo;re exploring a number
of ways. First, let&amp;rsquo;s break it in three correlated APIs: &lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;&lt;span style="font-family: Symbol;"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;Filter the catalog based on a predicate - method name?&lt;/li&gt;
&lt;li&gt;&lt;span style="font-family: Symbol;"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;Hold the true set and the false set - type name?&lt;/li&gt;
&lt;li&gt;&lt;span style="font-family: Symbol;"&gt;&lt;span&gt;&lt;/span&gt;&lt;/span&gt;Expose the false set - property name?&lt;/li&gt;
&lt;/ol&gt;
&lt;p class="MsoNormal"&gt;For the first, we are considering: Catalog.Filter,
.Partition and .Where. Remember, there&amp;rsquo;s no clear winner, all options have
drawbacks. &lt;b&gt;Filter&lt;/b&gt; does not convey that the result is two sets. &lt;b&gt;Partition&lt;/b&gt; is
quite mathematical, and may not elude that it can also be used for pure
filtering scenarios. &lt;b&gt;Where&lt;/b&gt; brings the mental model of Linq, but doesn&amp;rsquo;t return
IEnumerable&amp;lt;&amp;gt; so it may be abusing the mental model.&lt;/p&gt;
&lt;p class="MsoNormal"&gt;For the second, we&amp;rsquo;ve been debating over FilteredCatalog, PartitionedCatalog,
Tuple&amp;lt;Catalog,Catalog&amp;gt;, &lt;span&gt;&amp;nbsp;&lt;/span&gt;and
PairedCatalog. Note that the result of the aforementioned method is itself a
catalog, but a catalog with &amp;ldquo;extra&amp;rdquo; information, the false set.&lt;/p&gt;
&lt;p class="MsoNormal"&gt;Finally, for the false set we have considered a property
like Complement, PartsNotFiltered, DisjointSet. &lt;/p&gt;
&lt;p class="MsoNormal"&gt;Hard! &lt;b&gt;How would you design it?&lt;/b&gt;&lt;/p&gt;
&lt;p class="MsoNormal"&gt;&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10060048" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/hammett/archive/tags/MEF/">MEF</category></item><item><title>MEF features for v.next – feedback request</title><link>http://blogs.msdn.com/b/hammett/archive/2010/06/11/mef-features-for-v-next-feedback-request.aspx</link><pubDate>Fri, 11 Jun 2010 21:55:16 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10023748</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>12</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=10023748</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2010/06/11/mef-features-for-v-next-feedback-request.aspx#comments</comments><description>&lt;p&gt;We’re in planning phase for MEF for quite some time. I believe we have a very decent idea of things that needs improvement, and the priority of those. Of course, our team has limited resources so there are no promises whether we can actually ship any of those in the next MEF release. That said, it would be great if you could weight in and let us know what would you consider more valuable. Pick one or two items that you rather see us not shipping a v.next unless we add those. :-)&lt;/p&gt;  &lt;p&gt;Some ideas of features (feel free to suggest more)&lt;/p&gt;  &lt;ul&gt;   &lt;li&gt;- Convention-based discovery catalog &lt;/li&gt;    &lt;li&gt;- Explicit wiring &lt;/li&gt;    &lt;li&gt;- Generic instantiation (being able to export IRepository&amp;lt;&amp;gt; and import IRepository&amp;lt;Customer&amp;gt;) &lt;/li&gt;    &lt;li&gt;- Better diagnostics &lt;/li&gt;    &lt;li&gt;- AOP/Interceptors &lt;/li&gt;    &lt;li&gt;- Integration with XAML/WPF &lt;/li&gt;    &lt;li&gt;- Integration with Azure &lt;/li&gt;    &lt;li&gt;- Simplification of scoping/container hierarchy &lt;/li&gt;    &lt;li&gt;- Custom lifetimes (per thread, transactional) &lt;/li&gt; &lt;/ul&gt;  &lt;p&gt;&amp;#160;&lt;/p&gt;  &lt;p&gt;Anything I’ve missed?&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10023748" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/hammett/archive/tags/MEF/">MEF</category></item><item><title>MEF: What and why</title><link>http://blogs.msdn.com/b/hammett/archive/2010/05/29/mef-what-and-why.aspx</link><pubDate>Sat, 29 May 2010 15:23:57 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:10017307</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=10017307</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2010/05/29/mef-what-and-why.aspx#comments</comments><description>&lt;p&gt;So it’s been almost two years working for Microsoft and feels like several years. Not because I was able to accomplish much – I haven’t – but that things go in a different pace here. I learned to understand why that is, and how Microsoft can afford to pay smart people to solve tough problems. MEF is one of them. &lt;/p&gt;  &lt;p&gt;As a hardcore developer I’ve always approach projects as the ‘what’ and the feature set. As a PM I learned to have a broader view of things. I’ve also learned to lay down plans and really think through before writing a single line of code, but that deserves another post altogether. It took me quite some time to get past MEF as just a framework and understand where it fits in the bigger picture. I realize, though, that people in community are still asking the wrong questions. &lt;/p&gt;  &lt;p&gt;MEF is an IoC Container? That’s undeniable. It makes use of the same Inversion of Control principle that governs all IoC Containers out there. In the past, we tried hard to position it as not an IoC Container, but that was the wrong approach. What we really meant to say was that it’s not comparable to the usual suspects. Instead, it’s a very specialized one. If you want concrete points (applies to MEF out of the box):&lt;/p&gt;  &lt;p&gt;· We do not have the same extensibility points&lt;/p&gt;  &lt;p&gt;· We do not support manual/explicit wiring&lt;/p&gt;  &lt;p&gt;· We do not support any interception mechanism&lt;/p&gt;  &lt;p&gt;· We do not have any self-contained reusable extensibility mechanism, such as Windsor’s Facilities&lt;/p&gt;  &lt;p&gt;Behavior wise MEF also differs from the usual suspects. We value explicitness over conventions. We value discovery over registration code. We value static analyzability as a mean to support a rich tooling story.&lt;/p&gt;  &lt;h3&gt;The scenarios&lt;/h3&gt;  &lt;p&gt;Before saying “you guys suck” please allow me to explain you that MEF – as with most things that come from MS - is scenario-driven. We selected a handful of scenarios for version 1.0 based mostly on partner’s requirements and feedback and it was engineered to meet those. I’ll share a bit about them so you can understand where we came from, and where does MEF fit.&lt;/p&gt;  &lt;h4&gt;Open ended applications&lt;/h4&gt;  &lt;p&gt;IoC Containers are really engineered for “closed systems”. You know beforehand the set of components that will make your app, you control how they are wired up (bindings) and their configuration. In an open ended system you just know the set of components you are shipping but once that is deployed and new extensions start to be added, you cross your fingers and hope for the best. &lt;/p&gt;  &lt;p&gt;With that in mind, several decisions were made to make MEF a reliable technology for these kinds of scenarios. You certainly don’t want VS to crash if you happen to add a malfunction extension.&lt;/p&gt;  &lt;h4&gt;Stable composition&lt;/h4&gt;  &lt;p&gt;Stable composition is a feature introduced to deal exactly with this situation. It tries to pre-compose a graph and rejects pieces that will lead to a part that cannot be set up to its minimum requirements. If you were to use MEF as a standard IoC Container, though, this will eventually bite your development experience, especially if you’re not aware of it. &lt;/p&gt;  &lt;h4&gt;Reusing “parts” across application models&lt;/h4&gt;  &lt;p&gt;Imagine writing common parts that you could reuse in a Wpf, Silverlight, Console apps and ASP.NET apps. Of course, this part would have to make some diligence on the kind of dependencies it has from the external world. Any container specific behavior introduced by extension points or optional integrations could hurt this story. If parts were to depend on the container being set up to support a specific feature, then the reuse story would be compromised. That said, I believe it’s fair game to depend or support upon orthogonal/cross-cutting functionality.&lt;/p&gt;  &lt;h4&gt;Design-time diagnostics&lt;/h4&gt;  &lt;p&gt;Even though most people dislike MEF’s attributes, it allows us to build a rich tooling story that could help you to write extensions, predict errors and so forth. This is intended a productivity boost, not as a pain-reliever. &lt;/p&gt;  &lt;h3&gt;Beyond what: why?&lt;/h3&gt;  &lt;p&gt;Stepping back from the technology, MEF is a great tool for – at very minimum – two reasons:&lt;/p&gt;  &lt;p&gt;· It provides a ubiquitous way to expose extension points and consume extensions&lt;/p&gt;  &lt;p&gt;· It presents a minimal set of concepts that people should learn in order to deal with extensions&lt;/p&gt;  &lt;p&gt;Provided that, in time, the MEF gets the adoption it deserves from framework builders to app builders, we will see an interesting side effect: an ecosystem of extensions with degrees of reusability based on interdependencies. I believe that would be a huge win for us, the .net community, and look forward for this day. &lt;/p&gt;  &lt;p&gt;I also believe MEF is a great choice for framework builders. I intend to write a series of blog posts exemplifying this. Keep watching!&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=10017307" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/hammett/archive/tags/MEF/">MEF</category></item><item><title>MEF and ASP.NET MVC sample updated</title><link>http://blogs.msdn.com/b/hammett/archive/2009/07/15/mef-and-asp-net-mvc-sample-updated.aspx</link><pubDate>Wed, 15 Jul 2009 21:37:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9834550</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>8</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=9834550</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2009/07/15/mef-and-asp-net-mvc-sample-updated.aspx#comments</comments><description>&lt;p&gt;Sample updated to Preview 6. I've also took the time to simplify the MvcCatalog and to hard set the Creation Policy to Non Shared for all controllers.&lt;/p&gt;&lt;p&gt;&lt;br&gt;&lt;/p&gt;&lt;p&gt;Have fun!&amp;nbsp;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9834550" width="1" height="1"&gt;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-83-45-50/MvcWithMEF.zip" length="703655" type="application/x-zip-compressed" /></item><item><title>MEF and ASP.NET MVC sample</title><link>http://blogs.msdn.com/b/hammett/archive/2009/04/23/mef-and-asp-net-mvc-sample.aspx</link><pubDate>Thu, 23 Apr 2009 20:45:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9565170</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>19</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=9565170</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2009/04/23/mef-and-asp-net-mvc-sample.aspx#comments</comments><description>&lt;H4&gt;Disclaimer&lt;/H4&gt;
&lt;P&gt;First things first, don’t consider this sample an official sample. It is just something I’ve created to illustrate some capabilities of MEF when integrated with ASP.NET MVC in the user-level (as opposed to framework level).&lt;/P&gt;
&lt;P&gt;Also, if you would try to do this integration yourself, you’ll notice at some point that you’ll need to attach metadata to your controllers, so you can grab the right one on the controller factory. In this sample I provide a custom catalog that is aware of controllers, so it adds the metadata itself saving us the burden. Of course, this adds to complexity..&lt;/P&gt;
&lt;P&gt;As MEF targets the extensibility story, this sample is an ASP.NET MVC app that can be “augmented” by new modules. The main app is a shell with almost no functionality. New modules add navigation, controllers, services and consume the services are present on the system.&lt;/P&gt;
&lt;P&gt;The first extension module provide adds Wiki support to the main application. The second, a forum module.&lt;/P&gt;
&lt;P&gt;Bear in mind that everything is fake. I’m showing how to leverage the extensibilities capabilities of MEF, and not how to design a CMS, Forum or Wiki :-)&lt;/P&gt;
&lt;P&gt;In a real world app a similar extensibility mechanism in a web app would also have to deal with database/versioning issues, content resource (additional css, js, images), and so forth.&lt;/P&gt;
&lt;H4&gt;Download&lt;/H4&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/hammett/attachment/9565170.ashx"&gt;MvcWithMEF.zip&lt;/A&gt;&lt;/P&gt;
&lt;H4&gt;Walkthrough&lt;/H4&gt;
&lt;P&gt;You may start by running the app. You should see the following on your browser:&lt;/P&gt;
&lt;P&gt;&lt;A href="http://blogs.msdn.com/blogfiles/hammett/WindowsLiveWriter/MEFandASP.NETMVC_89BE/scl1_2.png" mce_href="http://blogs.msdn.com/blogfiles/hammett/WindowsLiveWriter/MEFandASP.NETMVC_89BE/scl1_2.png"&gt;&lt;IMG style="BORDER-RIGHT-WIDTH: 0px; DISPLAY: inline; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px" title=scl1 border=0 alt=scl1 src="http://blogs.msdn.com/blogfiles/hammett/WindowsLiveWriter/MEFandASP.NETMVC_89BE/scl1_thumb_1.png" width=640 height=458 mce_src="http://blogs.msdn.com/blogfiles/hammett/WindowsLiveWriter/MEFandASP.NETMVC_89BE/scl1_thumb_1.png"&gt;&lt;/A&gt;&lt;/P&gt;
&lt;P&gt;The links above (forum, wiki) were added dynamically by modules loaded. &lt;/P&gt;
&lt;H4&gt;&lt;/H4&gt;
&lt;H5&gt;Where everything starts&lt;/H5&gt;
&lt;P&gt;The Global.asax.cs holds our bootstrap code:&lt;/P&gt;
&lt;DIV class=csharpcode&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   1:  &lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;protected&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;void&lt;/SPAN&gt; Application_Start()&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   2:  &lt;/SPAN&gt;{&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   3:  &lt;/SPAN&gt;  HostingEnvironment.RegisterVirtualPathProvider(&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   4:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; AssemblyResourceVirtualPathProvider());&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   5:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   6:  &lt;/SPAN&gt;  RegisterRoutes(RouteTable.Routes);&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   7:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   8:  &lt;/SPAN&gt;  var catalog = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; CatalogBuilder().&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   9:  &lt;/SPAN&gt;    ForAssembly(&lt;SPAN class=kwrd&gt;typeof&lt;/SPAN&gt;(IModuleInstaller).Assembly).&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  10:  &lt;/SPAN&gt;    ForMvcAssembly(Assembly.GetExecutingAssembly()).&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  11:  &lt;/SPAN&gt;    ForMvcAssembliesInDirectory(HttpRuntime.BinDirectory, &lt;SPAN class=str&gt;"*Extension.dll"&lt;/SPAN&gt;). &lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  12:  &lt;/SPAN&gt;    Build();&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  13:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  14:  &lt;/SPAN&gt;  _container = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; CompositionContainer(catalog);&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  15:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  16:  &lt;/SPAN&gt;  var modules = _container.GetExportedObjects&amp;lt;IModuleInstaller&amp;gt;();&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  17:  &lt;/SPAN&gt;  var navService = _container.GetExportedObject&amp;lt;NavigationService&amp;gt;();&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  18:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  19:  &lt;/SPAN&gt;  InitializeModules(modules, navService);&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  20:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  21:  &lt;/SPAN&gt;  ControllerBuilder.Current.SetControllerFactory(&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  22:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; MefControllerFactory(_container));&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  23:  &lt;/SPAN&gt;}&lt;/PRE&gt;&lt;/DIV&gt;
&lt;STYLE type=text/css&gt;
.csharpcode, .csharpcode pre{	font-size: small;	color: black;	font-family: consolas, "Courier New", courier, monospace;	background-color: #ffffff;	/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {	background-color: #f4f4f4;	width: 100%;	margin: 0em;}.csharpcode .lnum { color: #606060; }&lt;/STYLE&gt;

&lt;P&gt;The first line sets up a custom VirtualPathProvider that check assembly resources for content. Nothing new. &lt;/P&gt;
&lt;P&gt;Lines 8-12 defines our catalog, which encapsulates the discovery mechanism on MEF. It also provides us opportunities to customize things. In this case, we want to discover things on the Core assembly (line 9), on the executing assembly/web project assembly (line 10), and anything on the web app’s bin folder that ends with Extension.dll (line 11). &lt;/P&gt;
&lt;P&gt;A container is created with a reference to the aggregation of all these catalogs. Right after we retrieve all IModuleInstaller implementations available and start all modules, which is to say we give them a chance to change/add URL routes and add navigation information. &lt;/P&gt;
&lt;P&gt;Finally, we create a custom IControllerFactory instance and set up ASP.NET MVC to use it (line 21).&lt;/P&gt;
&lt;H5&gt;The MEF Controller Factory&lt;/H5&gt;
&lt;DIV class=csharpcode&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   1:  &lt;/SPAN&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; MefControllerFactory : IControllerFactory&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   2:  &lt;/SPAN&gt;{&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   3:  &lt;/SPAN&gt;  &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;const&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; ControllerExportEntryName = &lt;SPAN class=str&gt;"controllerExport"&lt;/SPAN&gt;;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   4:  &lt;/SPAN&gt;  &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;readonly&lt;/SPAN&gt; CompositionContainer _container;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   5:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   6:  &lt;/SPAN&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; MefControllerFactory(CompositionContainer container)&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   7:  &lt;/SPAN&gt;  {&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;   8:  &lt;/SPAN&gt;    _container = container;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;   9:  &lt;/SPAN&gt;  }&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  10:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  11:  &lt;/SPAN&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; IController CreateController(RequestContext requestContext, &lt;SPAN class=kwrd&gt;string&lt;/SPAN&gt; controllerName)&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  12:  &lt;/SPAN&gt;  {&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  13:  &lt;/SPAN&gt;    var controllerExport = _container.GetExports&amp;lt;IController&amp;gt;().&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  14:  &lt;/SPAN&gt;      Where(exp =&amp;gt; &lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  15:  &lt;/SPAN&gt;        exp.Metadata.ContainsKey(Constants.ControllerNameMetadataName) &amp;amp;&amp;amp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  16:  &lt;/SPAN&gt;        exp.Metadata[Constants.ControllerNameMetadataName].&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  17:  &lt;/SPAN&gt;          ToString().ToLowerInvariant().&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  18:  &lt;/SPAN&gt;          Equals(controllerName.ToLowerInvariant())).&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  19:  &lt;/SPAN&gt;        FirstOrDefault();&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  20:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  21:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (controllerExport == &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;)&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  22:  &lt;/SPAN&gt;    {&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  23:  &lt;/SPAN&gt;      &lt;SPAN class=kwrd&gt;throw&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; HttpException(404, &lt;SPAN class=str&gt;"Not found"&lt;/SPAN&gt;);&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  24:  &lt;/SPAN&gt;    }&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  25:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  26:  &lt;/SPAN&gt;    requestContext.HttpContext.Items[ControllerExportEntryName] = controllerExport;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  27:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  28:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; controllerExport.GetExportedObject();&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  29:  &lt;/SPAN&gt;  }&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  30:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  31:  &lt;/SPAN&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;void&lt;/SPAN&gt; ReleaseController(IController controller)&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  32:  &lt;/SPAN&gt;  {&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  33:  &lt;/SPAN&gt;    var export = HttpContext.Current.Items[ControllerExportEntryName] &lt;SPAN class=kwrd&gt;as&lt;/SPAN&gt; Export&amp;lt;IController&amp;gt;;&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  34:  &lt;/SPAN&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  35:  &lt;/SPAN&gt;    &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (export != &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;)&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  36:  &lt;/SPAN&gt;    {&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  37:  &lt;/SPAN&gt;      _container.ReleaseExport(export);&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  38:  &lt;/SPAN&gt;    }&lt;/PRE&gt;&lt;PRE class=alt&gt;&lt;SPAN class=lnum&gt;  39:  &lt;/SPAN&gt;  }&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=lnum&gt;  40:  &lt;/SPAN&gt;}&lt;/PRE&gt;&lt;/DIV&gt;
&lt;STYLE type=text/css&gt;
.csharpcode, .csharpcode pre{	font-size: small;	color: black;	font-family: consolas, "Courier New", courier, monospace;	background-color: #ffffff;	/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {	background-color: #f4f4f4;	width: 100%;	margin: 0em;}.csharpcode .lnum { color: #606060; }&lt;/STYLE&gt;

&lt;P&gt;This implementation, albeit short, shows interests aspects. First, on the CreateController, we get all exports of IController – which is different from getting all _instances_ of IController. Then, we use the metadata associated with those Exports to find the controller we need to get an instance. &lt;/P&gt;
&lt;P&gt;We hold this export instance for the duration of this request (HttpContext.Items), so we can use it on ReleaseController. This relies on the assumption that in a request only one controller is instantiated. &lt;/P&gt;
&lt;P&gt;The ReleaseController get back that export instance and calls Container.ReleaseExport, which will go over all the object graph, and properly release and dispose NonShared / Disposable instances. If you miss this step you will be in a route to a memory bloat as every controller is non shared and disposable. &lt;/P&gt;
&lt;H5&gt;The MVC Catalog&lt;/H5&gt;
&lt;P&gt;This one is a bit more complex, but remember, it is an optional step. I just added it because I’m lazy and didn’t want to add metadata to every controller (it would be a violation of DRY too.) &lt;/P&gt;
&lt;DIV class=csharpcode&gt;&lt;PRE class=alt&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; MvcCatalog : ComposablePartCatalog, ICompositionElement&lt;/PRE&gt;&lt;PRE&gt;{&lt;/PRE&gt;&lt;PRE class=alt&gt;  &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;readonly&lt;/SPAN&gt; Type[] _types;&lt;/PRE&gt;&lt;PRE&gt;  &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;readonly&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;object&lt;/SPAN&gt; _locker = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;object&lt;/SPAN&gt;();&lt;/PRE&gt;&lt;PRE class=alt&gt;  &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; IQueryable&amp;lt;ComposablePartDefinition&amp;gt; _parts;&lt;/PRE&gt;&lt;PRE&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; MvcCatalog(&lt;SPAN class=kwrd&gt;params&lt;/SPAN&gt; Type[] types)&lt;/PRE&gt;&lt;PRE&gt;  {&lt;/PRE&gt;&lt;PRE class=alt&gt;    _types = types;&lt;/PRE&gt;&lt;PRE&gt;  }&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;  &lt;SPAN class=rem&gt;// More constructors //&lt;/SPAN&gt;&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;override&lt;/SPAN&gt; IQueryable&amp;lt;ComposablePartDefinition&amp;gt; Parts&lt;/PRE&gt;&lt;PRE class=alt&gt;  {&lt;/PRE&gt;&lt;PRE&gt;    get { &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; InternalParts; }&lt;/PRE&gt;&lt;PRE class=alt&gt;  }&lt;/PRE&gt;&lt;PRE&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;  &lt;SPAN class=kwrd&gt;internal&lt;/SPAN&gt; IQueryable&amp;lt;ComposablePartDefinition&amp;gt; InternalParts&lt;/PRE&gt;&lt;PRE&gt;  {&lt;/PRE&gt;&lt;PRE class=alt&gt;    get&lt;/PRE&gt;&lt;PRE&gt;    {&lt;/PRE&gt;&lt;PRE class=alt&gt;      &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (_parts == &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;)&lt;/PRE&gt;&lt;PRE&gt;      {&lt;/PRE&gt;&lt;PRE class=alt&gt;        &lt;SPAN class=kwrd&gt;lock&lt;/SPAN&gt;(_locker)&lt;/PRE&gt;&lt;PRE&gt;        {&lt;/PRE&gt;&lt;PRE class=alt&gt;          &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (_parts == &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;)&lt;/PRE&gt;&lt;PRE&gt;          {&lt;/PRE&gt;&lt;PRE class=alt&gt;            var partsCollection = &lt;/PRE&gt;&lt;PRE&gt;              &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; List&amp;lt;ComposablePartDefinition&amp;gt;();&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;            &lt;SPAN class=kwrd&gt;foreach&lt;/SPAN&gt;(var type &lt;SPAN class=kwrd&gt;in&lt;/SPAN&gt; _types)&lt;/PRE&gt;&lt;PRE class=alt&gt;            {&lt;/PRE&gt;&lt;PRE&gt;              var typeCatalog = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; TypeCatalog(type);&lt;/PRE&gt;&lt;PRE class=alt&gt;              var part = typeCatalog.Parts.FirstOrDefault();&lt;/PRE&gt;&lt;PRE&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;              &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (part == &lt;SPAN class=kwrd&gt;null&lt;/SPAN&gt;) &lt;SPAN class=kwrd&gt;continue&lt;/SPAN&gt;;&lt;/PRE&gt;&lt;PRE&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;              &lt;SPAN class=kwrd&gt;if&lt;/SPAN&gt; (&lt;SPAN class=kwrd&gt;typeof&lt;/SPAN&gt;(IController).IsAssignableFrom(type))&lt;/PRE&gt;&lt;PRE&gt;              {&lt;/PRE&gt;&lt;PRE class=alt&gt;                part = &lt;SPAN class=kwrd&gt;new&lt;/SPAN&gt; &lt;/PRE&gt;&lt;PRE&gt;                  ControllerPartDefinitionDecorator(&lt;/PRE&gt;&lt;PRE class=alt&gt;                    part, &lt;/PRE&gt;&lt;PRE&gt;                    type, &lt;/PRE&gt;&lt;PRE class=alt&gt;                    type.Name, &lt;/PRE&gt;&lt;PRE&gt;                    type.Namespace);&lt;/PRE&gt;&lt;PRE class=alt&gt;              }&lt;/PRE&gt;&lt;PRE&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;              partsCollection.Add(part);&lt;/PRE&gt;&lt;PRE&gt;            }&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;            Thread.MemoryBarrier();&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;            _parts = partsCollection.AsQueryable();&lt;/PRE&gt;&lt;PRE class=alt&gt;          }&lt;/PRE&gt;&lt;PRE&gt;        }&lt;/PRE&gt;&lt;PRE class=alt&gt;      }&lt;/PRE&gt;&lt;PRE&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE class=alt&gt;      &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; _parts;&lt;/PRE&gt;&lt;PRE&gt;    }&lt;/PRE&gt;&lt;PRE class=alt&gt;  }&lt;/PRE&gt;&lt;/DIV&gt;
&lt;STYLE type=text/css&gt;
.csharpcode, .csharpcode pre{	font-size: small;	color: black;	font-family: consolas, "Courier New", courier, monospace;	background-color: #ffffff;	/*white-space: pre;*/}.csharpcode pre { margin: 0em; }.csharpcode .rem { color: #008000; }.csharpcode .kwrd { color: #0000ff; }.csharpcode .str { color: #006080; }.csharpcode .op { color: #0000c0; }.csharpcode .preproc { color: #cc6633; }.csharpcode .asp { background-color: #ffff00; }.csharpcode .html { color: #800000; }.csharpcode .attr { color: #ff0000; }.csharpcode .alt {	background-color: #f4f4f4;	width: 100%;	margin: 0em;}.csharpcode .lnum { color: #606060; }&lt;/STYLE&gt;

&lt;P&gt;What we’re doing here is: for each type discovered – is a MEF part – we also check if it happens to be a controller. If so, we decorate that part to add an additional export. This export has all the extra metadata that we need to query for that controller later on. &lt;/P&gt;
&lt;H5&gt;&lt;/H5&gt;
&lt;H5&gt;Wiring&lt;/H5&gt;
&lt;P&gt;As we’re using MEF for extensibility we might just as well use it for typical composition – as long as our requirements are low compared to the use of a full fledge IoC Container. &lt;/P&gt;
&lt;DIV class=csharpcode&gt;&lt;PRE class=alt&gt;[Export, PartCreationPolicy(CreationPolicy.NonShared)]&lt;/PRE&gt;&lt;PRE&gt;&lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;class&lt;/SPAN&gt; ForumController : BasePublicController&lt;/PRE&gt;&lt;PRE class=alt&gt;{&lt;/PRE&gt;&lt;PRE&gt;  &lt;SPAN class=kwrd&gt;private&lt;/SPAN&gt; &lt;SPAN class=kwrd&gt;readonly&lt;/SPAN&gt; ForumService _forumService;&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;  [ImportingConstructor]&lt;/PRE&gt;&lt;PRE class=alt&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; ForumController(ForumService forumService)&lt;/PRE&gt;&lt;PRE&gt;  {&lt;/PRE&gt;&lt;PRE class=alt&gt;    _forumService = forumService;&lt;/PRE&gt;&lt;PRE&gt;  }&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;  &lt;SPAN class=kwrd&gt;public&lt;/SPAN&gt; ActionResult Index()&lt;/PRE&gt;&lt;PRE class=alt&gt;  {&lt;/PRE&gt;&lt;PRE&gt;    ViewData[&lt;SPAN class=str&gt;"forums"&lt;/SPAN&gt;] = _forumService.GetEnabledForumsRecentActivity();&lt;/PRE&gt;&lt;PRE class=alt&gt;&amp;nbsp;&lt;/PRE&gt;&lt;PRE&gt;    &lt;SPAN class=kwrd&gt;return&lt;/SPAN&gt; View(ViewRoot + &lt;SPAN class=str&gt;"Index.aspx"&lt;/SPAN&gt;);&lt;/PRE&gt;&lt;PRE class=alt&gt;  }&lt;/PRE&gt;&lt;PRE&gt;}&lt;/PRE&gt;&lt;/DIV&gt;
&lt;P&gt;In this controller we import (depend) ForumService, which itself depends on IForumRepository. If you don’t mind the extra noise of attributes, MEF can also cover this aspect of your app – but remember, it wasn’t built to be an IoC Container as the ones out there – more on that in another day. &lt;/P&gt;
&lt;H4&gt;Conclusion&lt;/H4&gt;
&lt;P&gt;In the user-level integration MEF plays very well with ASP.NET MVC to enable extensibility on web apps. Of course, this is not the whole story. Like I mentioned, database schema updates/version, making additional content available (js, css, images) and UI Composition are challenging things themselves, but solvable – been there, done that. &lt;/P&gt;
&lt;P&gt;With MEF you have one less thing to worry about in this challenging problem space. &lt;/P&gt;
&lt;P&gt;&lt;STRONG&gt;Update:&lt;/STRONG&gt; Kamil spot the fact that my decorator is leaving out one member, and that essentially makes it ignore the creation policy (which is attached to the part definition, not exports). Sample updated.&lt;/P&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9565170" width="1" height="1"&gt;</description><enclosure url="http://blogs.msdn.com/cfs-file.ashx/__key/communityserver-components-postattachments/00-09-56-51-70/MvcWithMEF.zip" length="685522" type="application/x-zip-compressed" /></item><item><title>Dependencies, ownership and lifetime</title><link>http://blogs.msdn.com/b/hammett/archive/2008/10/16/dependencies-ownership-and-lifetime.aspx</link><pubDate>Fri, 17 Oct 2008 01:15:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:9002444</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>0</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=9002444</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2008/10/16/dependencies-ownership-and-lifetime.aspx#comments</comments><description>&lt;P&gt;First of all, this blog post contains my own views and does not necessarily reflect the view of employer.&lt;/P&gt;
&lt;P&gt;MEF is a complex small project, dealing with a big and complex problem. In our team a feature crew - a PM, dev and tester - owns a feature. We research, brainstorm, prototype to exhaustion, come up with real world scenarios, brainstorm some more and then finally a spec is produced (or finalized). I'm on the lifetime feature crew. Our goal is to decide and propose a solution on how MEF should deal with lifetime. &lt;/P&gt;
&lt;P&gt;There is a broad range of possible solutions, from not supporting anything at all (which is a valid option) to support a full extensible (and possibly complex) lifetime story. Things to consider are:&lt;/P&gt;
&lt;P&gt;- Being part of the core framework comes with responsabilities. All dogmas should be left on the door, and a solution should be compatible with how the rest of the framework (and its guidelines)&lt;BR&gt;- MEF is not an full fledge IoC, and as such it shouldn't need to behave as one&lt;BR&gt;- The final solution should translate into a predictable behavior for users (more on that below)&lt;/P&gt;
&lt;P&gt;The rest of the post is me sharing (with authorization) some of our findings, some of tough calls to make, and kindly asking for feedback :-)&lt;/P&gt;
&lt;P&gt;In case you're not familiar, lifetime is a concept widely used on component frameworks, especially IoC containers. However it's not 100% adopted, and it might use different names. It defines the scope of accessibility and how (or better, if) an instance can be shared. Singleton is a common lifetime. So is Transient. &lt;/P&gt;
&lt;P&gt;Windsor (and back to Apache Avalon/Excalibur) refers to them as lifestyle instead, and supports Singleton, Transient, Pooled, PerThread and PerWebRequest out of box. It's relatively easy to add a new one. Spring supports Singleton and Transient (which it calls Prototype). The Java version of spring brings extensibility points so you can add new ones. PicoContainer supports only Singletons - new lifetimes can be supported using child container (and carefully registering the components on correctly in the container hierarchy). Autofac supports both singleton and transient, and also relies on container hierarchies to support others.&amp;nbsp; &lt;/P&gt;
&lt;P&gt;Outside of the realm of IoC container you can still see similar concepts on OSGi, EJB, COM+ and .Net Remoting. Take the last as a more reachable example, the WellKnownObjectMode enum reads Singleton, SingleCall, which is essentially the same Singleton/Transient pair supported by some IoC containers. &lt;/P&gt;
&lt;P&gt;All is good, but then you face the challenges that this simple concept brings with it.&lt;/P&gt;
&lt;H2&gt;Incompatible Lifetimes &lt;/H2&gt;
&lt;P&gt;Not all lifetimes are compatible with each other. You won't have problems as long as it goes bottom up, from most restricted lifetimes depending on things served but more broad lifetimes. For instance, it's OK to have a per-web-request component that has a dependency on a per-session lifetime, which itself has dependencies on singletons. The opposite is not true, though. &lt;/P&gt;
&lt;H2&gt;Lifetimes that maps to non-boundaries context &lt;/H2&gt;
&lt;P&gt;Singletons can be mapped to the life of the container. You shutdown the container and all singletons are shutdown too. Per-session has a clearly boundary (session starts/ends) and so does per-web-request. &lt;/P&gt;
&lt;P&gt;What about Transients? They can be map to the container lifetime too, but would that mean that we only shutdown them when the container is disposed? That would lead to growing memory consuption in some apps scenarios. What about per-thread? Do we get a notification we a thread is about to start and when it's about to die? &lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;H2&gt;Ownership &lt;/H2&gt;
&lt;P&gt;This is not entirely related to lifetime, rather a common OOP problem. Usually you're forced to read the documentation to find out how you're suppose to deal with an object under a particular situation, as the API usually wont be able to tell you. Consider the following:&lt;/P&gt;&lt;PRE&gt;FileStream fs = ...

var processor = new FileProcessor(fs);
processor.Process();&lt;/PRE&gt;
&lt;P&gt;FileStream clearly needs to be disposed. By externally creating it and passing to some other object, do you implicitly transfer the ownership? Some will say yes, some will say no. Others will go with "depends". &lt;/P&gt;
&lt;P&gt;IMHO, for the sample above you do not transfer ownership, so the creator (you) have to dispose it. However if the FileProcessor itself created the FileStream, than it would have the ownership and the obligation to dispose it. Yes, I know, we have finalizers, but the way I see they are safeguards more than anything else. I'll come back to this.&lt;/P&gt;
&lt;P&gt;Fixing our code:&lt;/P&gt;&lt;PRE&gt;using(FileStream fs = ...)
{
&amp;nbsp;&amp;nbsp;&amp;nbsp; var processor = new FileProcessor(fs);
&amp;nbsp;&amp;nbsp;&amp;nbsp; processor.Process();
}
&lt;/PRE&gt;
&lt;P&gt;The devil is in the details, though. What if FileProcessor is a long lived instance, that process the file in response to some external stimulus? In that case, the code above will early dipose a stream that the processor will need later.&amp;nbsp; &lt;BR&gt;&amp;nbsp;&lt;BR&gt;Yeah, things are not as easy as they seem. You can come up with something that defines clear contracts, though:&lt;/P&gt;&lt;PRE&gt; 
var processor = new FileProcessor(new FileAccessor(new DirectoryInfo("./files")));
&lt;/PRE&gt;&lt;BR&gt;&amp;nbsp;&lt;BR&gt;Depending on the FileAccessor API it would be more or less clear whose the ownership of file. 
&lt;P&gt;A stream is a relatively straingforward example as it's something that is clearly unshareable. Now consider an even worse situation:&lt;/P&gt;&lt;PRE&gt;var sender = new FtpSender();

var backupSvc = new BackupService(sender);
var docBrw = new DocumentUploaderService(sender);
&lt;/PRE&gt;
&lt;P&gt;FtpSender implements IDisposable, which closes the outgoing transfers and the main connection. Should the dependant services ever dispose them? Clearly no, as it's being shared. But how will the BackupService ever know it's shared? Same thing applies for DocumentUploaderService.&lt;/P&gt;
&lt;P&gt;As someone who things conventions (and by consequence guidelines) tend to result in good things, I'd say that it would be safer to rely on a simple convetion: whoever created something has the obligation of destroying it. Obviously that will only apply to instances that have some sort of shutdown semantics like Stop, Close or Dispose. &lt;/P&gt;
&lt;P&gt;Bringing all that to IoC containers. Windsor has always encouraged that. You don't care how things ended up on your constructor or properties, and you shouldn't care. In order words: &amp;lt;b&amp;gt;Thou shall shutdown them explicitly&amp;lt;/b&amp;gt;.&lt;/P&gt;
&lt;P&gt;Spring, however, deals with shutdown semantics for singleton, but leaves it up to you in the case of transients. I disagree with this as I find troublesome to have to know the lifetime of my dependencies and act accordingly - IMHO I shouldn't have to care - but I deeply understand their reasons. Here's why:&lt;/P&gt;
&lt;P&gt;First, in order to shutdown short lived instances, you need to expose an operation to do that. Windsor and Ninject expose a Release method on the container interface. &amp;lt;i&amp;gt;What happens if the user doesn't call it? &amp;lt;/i&amp;gt;&lt;/P&gt;
&lt;P&gt;Secondly, imagine that you have instances that don't care for shutdown, but later on on the dependency chain there's a instance who cares. Guess what. You'll need to keep a chain of references in order to dispose that last one - what I like to call component burden (there is room for optimizations on the implementation algorithm, though). Why you need the chain? Because Release will be called on the first (root) instance. &lt;/P&gt;
&lt;P&gt;So all in all, while it's easy to put an statement defining how ownership should be handled it does make things _way_ complex. There's a balance however, on what is the right behavior we should strive for, and what's a problem without a good solution that we shouldn't spend energy trying to fix as there is no fix good enough anyway. &lt;/P&gt;
&lt;P&gt;What about the finalizer? Like I said, it's a good safe guard, but I rarely use it. You should be aware that instantiating an object that uses finalizer is more expensive. Also, in the call to finalizer I'm not supposed to reference other instances (ie dispose things other than wild unmanaged resource) as there is not invocation ordering guaranted. Maybe I'm spoilled by the fact that I've always relied on IoC container to do the proper shutdown for me. Implementing IStartable and IDisposable always meant that Windsor will call them, in the right time. Not having to rely on "what if" situations made my code simpler and allowed me to focus on other things. Boilerplate is for frameworks, my code should be about domain. &lt;/P&gt;
&lt;P&gt;Now, I'm interested in hear from you basically two things:&lt;/P&gt;
&lt;P&gt;- Do you often rely on shutdown semantics on your components?&lt;BR&gt;- What do you fell MEF should support?&lt;/P&gt;
&lt;P mce_keep="true"&gt;&amp;nbsp;&lt;/P&gt;
&lt;P&gt;&lt;BR&gt;&amp;nbsp;&lt;/P&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=9002444" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/hammett/archive/tags/MEF/">MEF</category></item><item><title>Introductions</title><link>http://blogs.msdn.com/b/hammett/archive/2008/08/13/introductions.aspx</link><pubDate>Thu, 14 Aug 2008 09:07:00 GMT</pubDate><guid isPermaLink="false">91d46819-8472-40ad-a661-2c78acb4018c:8864889</guid><dc:creator>hammett [MSFT]</dc:creator><slash:comments>1</slash:comments><wfw:commentRss xmlns:wfw="http://wellformedweb.org/CommentAPI/">http://blogs.msdn.com/b/hammett/rsscomments.aspx?WeblogPostID=8864889</wfw:commentRss><comments>http://blogs.msdn.com/b/hammett/archive/2008/08/13/introductions.aspx#comments</comments><description>&lt;p&gt;If you don't know me my name is Hamilton Verissimo, and I recently joined the MEF team at MS (DevDiv). I'll use this blog to talk about MEF and - give me some time to settle in - other things I plan to be involved with.&amp;nbsp; &lt;/p&gt;&lt;p&gt;&amp;nbsp;&lt;/p&gt;&lt;p&gt;My &lt;a href="http://hammett.castleproject.org/" mce_href="http://hammett.castleproject.org/"&gt;other blog&lt;/a&gt; will be kept but exclusively for Castle related stuff. &lt;br&gt;&lt;/p&gt;&lt;div style="clear:both;"&gt;&lt;/div&gt;&lt;img src="http://blogs.msdn.com/aggbug.aspx?PostID=8864889" width="1" height="1"&gt;</description><category domain="http://blogs.msdn.com/b/hammett/archive/tags/General/">General</category></item></channel></rss>