<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>var Matt = new Hero();</title>
	
	<link>http://www.fidelitydesign.net</link>
	<description>C#, ASP.NET MVC, MEF, Javascript...and anything else that interests me.</description>
	<lastBuildDate>Thu, 02 Sep 2010 23:35:21 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/FidelityDesign" /><feedburner:info uri="fidelitydesign" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><geo:lat>50.8073</geo:lat><geo:long>-0.3804</geo:long><item>
		<title>The Magic of IoC</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/2OWdZBMA-Xo/</link>
		<comments>http://www.fidelitydesign.net/?p=192#comments</comments>
		<pubDate>Wed, 25 Aug 2010 19:29:37 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[container]]></category>
		<category><![CDATA[inversion of control]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[strategy]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=192</guid>
		<description><![CDATA[
I was bored&#8230;
&#8230;so I decided to design an IoC Container! This actually turned out to be a lot of fun too. I&#8217;d like to firstly state that a) there is no reason for this code, and b) this is not a replacement for established IoC solutions, such as Unity, Castle Windsor, Ninject, Authofac, StructureMap, and [...]]]></description>
			<content:encoded><![CDATA[<p><!--9cb3f4ed8ccb4cde8ea942af170f24d2--></p>
<p>I was bored&#8230;</p>
<p>&#8230;so I decided to design an IoC Container! This actually turned out to be a lot of fun too. I&#8217;d like to firstly state that a) there is no reason for this code, and b) this is not a replacement for established IoC solutions, such as Unity, Castle Windsor, Ninject, Authofac, StructureMap, and lastly c) this is not production code. Ah, that&#8217;s better.</p>
<h3>The need for Inversion of Control (IoC)</h3>
<p>Inversion of Control (IoC) is not a new concept, it&#8217;s been around for quite a while, and many will be familiar with some of the IoC containers listed above. IoC is the concept changing the behaviour of a software system to allow decoupling of components within the framework.  The way I always understood IoC is that in a traditional software design, you may have a central piece of code which essentially orders other bits of code to do things specifically. I.e. &#8220;you do that, with this, and you do that, with this other bit&#8221;; in a software design that implements IoC, the central piece of code no longer orders the other bits round, rather the component requests an instance of a type so it can perform exactly what is is required to do, i.e. &#8220;can I have that, as I need to do this&#8221;.</p>
<p>This design pattern allows us to greatly modularise <strong>and</strong> decouple the components within our system.  If we wanted to, we can rip one part out, and throw in another part.  The dependant components are none the wiser.  Now if you google (or bing!), you will find plenty of articles describing IoC in much fuller detail, so I won&#8217;t bore you here other than to say, IoC can benefit a software design greatly, allowing you to somewhat future-proof your code, plus increase testability and greatly segregate logical portions of code without having to worry about all that &#8220;wire-up&#8221;.</p>
<h3>IoC Containers</h3>
<p>IoC Containers are fabulous bits of code.  They hide away the complexities of type management and they also handle dependancy injection (DI) for you. DI is the final piece of glue, it allows our containers to create our requested types without us (the developers) having to worry about explicity creating arguments for type construction (Constructor Injection), or member values (Property Injection).  If you have your types registered with your favourite IoC container, then the container should automatically be able to create the appropriate types and inject them into the type being created.  Let&#8217;s have a look at a quick example:</p>
<pre class="brush: csharp">
public class ConsoleLogger : ILogger
{
  public ConsoleLogger(IObjectFormatter formatter)
  {
    // Stuff here...
  }
}
</pre>
<p>In the simple code above, we have a class, the ConsoleLogger.  It&#8217;s only task is write objects to the console window.  Now, I&#8217;ve introduce a dependancy, an instance of IObjectFormatter that will be used to format the objects before the ConsoleLogger writes them to the output.  Because this is a required dependancy, I&#8217;ve made it part of the constructor.  If all goes well and I have registered an instance of IObjectFormatter with my container, when my container resolves my request for an ILogger, it should be able to create an instance of it, and inject the available IObjectFormatter into the constructor.  I haven&#8217;t had to worry about any of that! Genius.</p>
<h3>A simple IoC Container</h3>
<p>Ok, so onto the good stuff. There wasn&#8217;t any real reason for me to design my IoC container, I just wanted to see if I could do it! It was one of those &#8220;challenge-yourself&#8221; moments, and I think I won! Now, its not a perfect design, so I&#8217;m hoping I get quite a lot of constructive criticism too.</p>
<p>There are 3 major parts to this IoC design; IContainer, IBuildStrategy and ILifetimeStrategy.  The container is pretty obvious, but what are the other parts I hear you not ask?</p>
<p><strong>IBuildStrategy</strong><br />
A build strategy is responsible purely for creation of types.  This is where objects are built, and wars are won.  Here is the interface:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Defines the required contract for implementing a build strategy.
/// &lt;/summary&gt;
public interface IBuildStrategy
{
    #region Methods
    /// &lt;summary&gt;
    /// Creates an instance of the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type to create.&lt;/param&gt;
    /// &lt;param name="container"&gt;The current container.&lt;/param&gt;
    /// &lt;returns&gt;An instance of the specified type.&lt;/returns&gt;
    object CreateInstance(Type type, IContainer container);
    #endregion
}
</pre>
<p>It&#8217;s a simple interface, needing only the type to create, and the current container.  This design supports a single build strategy per type, and bundles three pre-built strategies:</p>
<ul>
<li><strong>DefaultBuildStrategy</strong> &#8211; This will create an instance of a type using the default public constructor.</li>
<li><strong>ConstructorBuildStrategy</strong> &#8211; This will create an instance of a type using a constructor with parameters, or a parameterless constructor that is not public.  This will resolve dependancies using the current container and inject them into the required constructor.</li>
<li><strong>InstanceBuildStrategy</strong> &#8211; This always returns the exact same instance each time, and is used when you register a type with a pre-built instance.</li>
</ul>
<p>Ok, they probably could have been named better&#8230;</p>
<p><strong>ILifetimeStrategy</strong><br />
A lifetime strategy is responsible for managing the lifetime of an instance created by the container. By default, this design ships with two strategies:</p>
<ul>
<li><strong>SingletonLifetimeStrategy</strong> &#8211; Manages a single isntance of a type for the lifetime of the container.  Any calls always result in the same instance being returned.</li>
<li><strong>AlwaysCreateLifetimeStrategy</strong> &#8211; Always creates a new instance using a build strategy for every call to resolve.</li>
</ul>
<p>The interface is a little more developed:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Defines the required contract for implementing a lifetime strategy.
/// &lt;/summary&gt;
public interface ILifetimeStrategy : IDisposable
{
    #region Methods
    /// &lt;summary&gt;
    /// Resolves an instance of the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type to resolve.&lt;/param&gt;
    /// &lt;param name="container"&gt;The current container.&lt;/param&gt;
    /// &lt;param name="build"&gt;The build strategy used to create an instance of the type.&lt;/param&gt;
    /// &lt;returns&gt;A resolves instance of the specified type.&lt;/returns&gt;
    object Resolve(Type type, IContainer container, IBuildStrategy build);

    /// &lt;summary&gt;
    /// Registers an object modifier with the lifetime strategy.
    /// &lt;/summary&gt;
    /// &lt;param name="modifier"&gt;The modifier to register.&lt;/param&gt;
    void RegisterModifier(IObjectModifier modifier);
    #endregion
}
</pre>
<p>Ignoring the RegisterModifier stuff, we can see that a lifetime strategy must resolve an instance.  I didn&#8217;t call this method &#8220;Create&#8221;, because it may not be creating an instance.  We pass in a build strategy for it to use if it needs to create an instance.</p>
<p>By combining these interfaces, we now have a mechanism for instance lifetime management and instance creation, two essential building blocks for an IoC container.</p>
<h3>Building the container</h3>
<p>Well, we have our under pinnings, but how does the container make use of it all?  Well, lets have a look at the interface:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Defines the required contract for implementing a container.
/// &lt;/summary&gt;
public interface IContainer
{
    #region Events
    /// &lt;summary&gt;
    /// Fired when a component is registered with the container.
    /// &lt;/summary&gt;
    event EventHandler&lt;RegistrationEventArgs&gt; ComponentRegistered;
    #endregion

    #region Properties
    /// &lt;summary&gt;
    /// Gets the default lifetime strategy to use.
    /// &lt;/summary&gt;
    LifetimeStrategy DefaultLifetimeStrategy { get; set; }
    #endregion

    #region Methods
    /// &lt;summary&gt;
    /// Gets the build strategy for the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;Gets the build strategy for the specified type.&lt;/param&gt;
    /// &lt;returns&gt;A &lt;see cref="IBuildStrategy"/&gt; for the specified type.&lt;/returns&gt;
    IBuildStrategy GetBuildStrategy(Type type);

    /// &lt;summary&gt;
    /// Gets an instance of the specified type.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;The type of instance to get.&lt;/typeparam&gt;
    /// &lt;returns&gt;An instance of the specified type, or the default if no instance can be created.&lt;/returns&gt;
    T GetInstance&lt;T&gt;();

    /// &lt;summary&gt;
    /// Gets an instance of the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type of instance to get.&lt;/param&gt;
    /// &lt;returns&gt;An instance of the specified type, or the default if no instance can be created.&lt;/returns&gt;
    object GetInstance(Type type);

    /// &lt;summary&gt;
    /// Gets all instances of the specified type.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;The type of instance to get.&lt;/typeparam&gt;
    /// &lt;returns&gt;An enumerable of available instances of the specified type.&lt;/returns&gt;
    IEnumerable&lt;T&gt; GetInstances&lt;T&gt;();

    /// &lt;summary&gt;
    /// Gets all instances of the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type of instance to get.&lt;/param&gt;
    /// &lt;returns&gt;An enumerable of available instances of the specified type.&lt;/returns&gt;
    IEnumerable&lt;object&gt; GetInstances(Type type);

    /// &lt;summary&gt;
    /// Gets the lifetime strategy for the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type to get a lifetime strategy for.&lt;/param&gt;
    /// &lt;returns&gt;A &lt;see cref="ILifetimeStrategy"/&gt; for the specified type.&lt;/returns&gt;
    ILifetimeStrategy GetLifetimeStrategy(Type type);

    /// &lt;summary&gt;
    /// Gets all lifetime strategies for the given type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type to get lifetime strategies for.&lt;/param&gt;
    /// &lt;returns&gt;An enumerable of lifetime strategies for the given type.&lt;/returns&gt;
    IEnumerable&lt;ILifetimeStrategy&gt; GetLifetimeStrategies(Type type);

    /// &lt;summary&gt;
    /// Creates a type registration for the specified type.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;The type of instance to create a registration for.&lt;/typeparam&gt;
    /// &lt;returns&gt;An &lt;see cref="IRegistration{T}"/&gt; for the given type.&lt;/returns&gt;
    IRegistration&lt;T&gt; Register&lt;T&gt;();

    /// &lt;summary&gt;
    /// Registers a build strategy for the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="type"&gt;The type to register a lifetime strategy for.&lt;/param&gt;
    /// &lt;param name="strategy"&gt;The strategy used to create instances.&lt;/param&gt;
    void RegisterBuildStrategy(Type type, IBuildStrategy strategy);

    /// &lt;summary&gt;
    /// Registers a lifetime strategy for the specified type.
    /// &lt;/summary&gt;
    /// &lt;param name="sourceType"&gt;The source type to register a lifetime strategy for.&lt;/param&gt;
    /// &lt;param name="targetType"&gt;The target type to register a lifetime strategy for.&lt;/param&gt;
    /// &lt;param name="strategy"&gt;The strategy used for lifetime management.&lt;/param&gt;
    void RegisterLifetimeStrategy(Type sourceType, Type targetType, ILifetimeStrategy strategy);
    #endregion
}
</pre>
<p>Ok, so we have the usual suspects&#8230;GetInstance, GetInstances, Register etc.  If you&#8217;ve been exposed to other IoC containers, or even service locators, this should all be familiar.  We then have methods like RegisterBuildStrategy, RegisterLifetimeStrategy.  The real meat of the work for registering a type is done from the RegisterLifetimeStrategy method.  It will create a binding between the source and target types, and the requested lifetime strategy.</p>
<p>The RegisterBuildStrategy is optional, it allows for a build strategy to be registered ahead of any types being resolved, this enables you to customise how your types are created.  If no build strategy exists for a type being resolved, the target type will by analysed to figure out how it should be built and generate a build strategy for you.</p>
<h3>How to configure</h3>
<p>The one inescapable drawback of most IoC solutions is that it can be quite tedious to configure all the necessary components.  This has been somewhat solved by approaches made by frameworks such as the Managed Extensibility Framework (MEF).  MEF is all about composition and promotes type discovery ahead of configuration.  I haven&#8217;t done any type discovery, so that means its back to configuration <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>This IoC design offers two ways to configure.  Either using the configuration system, or fluently (that&#8217;s the buzzword, right?) in code.  The configuration method allows you to configure multiple container setups in xml, which means if you wanted, you could have multiple container setups for different scenarios.  Here is a sample configuration:</p>
<pre class="brush: xml">
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;configuration&gt;
  &lt;configSections&gt;
    &lt;section name="ioc" type="SimpleIoC.Configuration.IoCConfigurationSection, SimpleIoC"/&gt;
  &lt;/configSections&gt;

  &lt;ioc&gt;
    &lt;!-- Containers --&gt;
    &lt;containers&gt;
      &lt;container name="default"&gt;
        &lt;sourceTypes&gt;
          &lt;add name="ILogger" type="SimpleIoC.Console.ILogger, SimpleIoC.Console" /&gt;
        &lt;/sourceTypes&gt;

        &lt;targetTypes&gt;
          &lt;add name="ConsoleLogger" sourceType="ILogger" targetType="SimpleIoC.Console.ConsoleLogger, SimpleIoC.Console" /&gt;
        &lt;/targetTypes&gt;
      &lt;/container&gt;
    &lt;/containers&gt;
  &lt;/ioc&gt;
&lt;/configuration&gt;
</pre>
<p>Relatively simple example, but you get the point.  There are some niceties in the current version, it allows you to establish named types so you don&#8217;t have to put the full type names in each time, as well as supporting build and lifetime strategy declarations&#8230;that really needs some more work&#8230;</p>
<h3>Getting fluent</h3>
<p>Fluency has become a natural progression of programming design recently, and this model is no different.  Let&#8217;s look at an example:</p>
<pre class="brush: csharp">
container.Register&lt;ILogger&gt;()
            .Using&lt;ConsoleLogger&gt;()
            .With(l =&gt; l.SomeProperty, "Hello World")
            .WithAppSetting(l =&gt; l.SomeOtherProperty, "SomeAppSettingKey");
</pre>
<p>With fluency, we get a very expressive way of configuring individual components.  There are many ways we could expand on this, but you get the idea.</p>
<h3>Where do we go from here</h3>
<p>Who knows really, there was no real goal here, I didn&#8217;t set out to &#8220;create one IoC container to rule them all&#8221;, it was purely an experiment to see if I could do it.  And so to that end, you&#8217;ll find the Visual Studio 2010 project (.NET 4.0 target) attached to the end of this blog post.  Please, I welcome any feedback, if I&#8217;ve wasted my time doing this, it&#8217;s good to know.  For those interested in IoC design, this could be a starting point.  It&#8217;s certainly been a learning experience for me! Peace.</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2010/08/SimpleIoC.zip'>SimpleIoC</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192&amp;title=The+Magic+of+IoC" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192&amp;title=The+Magic+of+IoC" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192&amp;title=The+Magic+of+IoC" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192&amp;headline=The+Magic+of+IoC" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=The+Magic+of+IoC&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=The+Magic+of+IoC&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=The+Magic+of+IoC&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=The+Magic+of+IoC&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=The+Magic+of+IoC&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192&amp;title=The+Magic+of+IoC&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D192" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=2OWdZBMA-Xo:QIsuYSyZ-Rg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=2OWdZBMA-Xo:QIsuYSyZ-Rg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=2OWdZBMA-Xo:QIsuYSyZ-Rg:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=2OWdZBMA-Xo:QIsuYSyZ-Rg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=2OWdZBMA-Xo:QIsuYSyZ-Rg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=2OWdZBMA-Xo:QIsuYSyZ-Rg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=2OWdZBMA-Xo:QIsuYSyZ-Rg:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=2OWdZBMA-Xo:QIsuYSyZ-Rg:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/2OWdZBMA-Xo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=192</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=192</feedburner:origLink></item>
		<item>
		<title>Integrating Regula with ASP.NET MVC and DataAnnotations</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/weCgZSy55lg/</link>
		<comments>http://www.fidelitydesign.net/?p=180#comments</comments>
		<pubDate>Tue, 17 Aug 2010 19:49:23 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[dataannotations]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[regula]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=180</guid>
		<description><![CDATA[Previously I discovered Regula, an annotation-based validation framework used for client-side validation of form elements.  I wondered if it was possible to automatically wire up client-side validation using DataAnnotation&#8217;s ValidationAttributes on the server side, very similar to how xVal might handle it.
This is by no means usable, its really an experiment to see what [...]]]></description>
			<content:encoded><![CDATA[<p>Previously I discovered Regula, an annotation-based validation framework used for client-side validation of form elements.  I wondered if it was possible to automatically wire up client-side validation using DataAnnotation&#8217;s ValidationAttributes on the server side, very similar to how xVal might handle it.</p>
<p>This is by no means usable, its really an experiment to see what is possible.</p>
<h3>Resolving ValidationAttributes us Regula constraints</h3>
<p>Right, first things first, we need some way of mapping between a ValidationAttribute, and its representation as a Regula constraint. To do this, we can create an interface contract which simply resolves an attribute as a constraint:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Defines the required contract for implementing a Regula attribute resolver.
/// &lt;/summary&gt;
public interface IAttributeResolver
{
    #region Methods
    /// &lt;summary&gt;
    /// Resolves the specified attribute as a Regula constraint.
    /// &lt;/summary&gt;
    /// &lt;param name="attribute"&gt;The attribute to resolve.&lt;/param&gt;
    /// &lt;returns&gt;The resolved constraint.&lt;/returns&gt;
    string Resolve(ValidationAttribute attribute);
    #endregion
}
</pre>
<p>Next, we need to create a type resposible for calling these resolvers, so we&#8217;ve created the RegulaAdapter. This type will have a collection of registered resolvers that are mapped against attribute types:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Provides an adapter for translating validation attributes to Regula constraints.
/// &lt;/summary&gt;
/// &lt;typeparam name="TModel"&gt;The model type.&lt;/typeparam&gt;
public class RegulaAdapter&lt;TModel&gt;
{
    #region Fields
    private static readonly IDictionary&lt;Type, IAttributeResolver&gt; Resolvers;
    #endregion

    #region Constructor
    /// &lt;summary&gt;
    /// Statically initialises the &lt;see cref="RegulaAdapter{TModel}"/&gt; type.
    /// &lt;/summary&gt;
    static RegulaAdapter()
    {
        Resolvers = new Dictionary&lt;Type, IAttributeResolver&gt;();
        RegisterDefaultResolvers();
    }
    #endregion

    #region Methods
    /// &lt;summary&gt;
    /// Registers an attribute resolver for the specified attribute.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TAttribute"&gt;The type of attribute.&lt;/typeparam&gt;
    /// &lt;typeparam name="TResolver"&gt;The type of resolver.&lt;/typeparam&gt;
    public static void RegisterResolver&lt;TAttribute, TResolver&gt;()
        where TAttribute : ValidationAttribute
        where TResolver: IAttributeResolver, new()
    {
        RegisterResolver&lt;TAttribute, TResolver&gt;(new TResolver());
    }

    /// &lt;summary&gt;
    /// Registers an attribute resolver for the specified attribute.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TAttribute"&gt;The type of attribute.&lt;/typeparam&gt;
    /// &lt;typeparam name="TResolver"&gt;The type of resolver.&lt;/typeparam&gt;
    /// &lt;param name="resolver"&gt;The instance of resolver to register.&lt;/param&gt;
    public static void RegisterResolver&lt;TAttribute, TResolver&gt;(TResolver resolver)
        where TAttribute : ValidationAttribute
        where TResolver : IAttributeResolver
    {
        var type = typeof(TAttribute);

        if (Resolvers.ContainsKey(type))
            Resolvers[type] = resolver;
        else
            Resolvers.Add(type, resolver);
    }

    /// &lt;summary&gt;
    /// Registers any default resolvers.
    /// &lt;/summary&gt;
    private static void RegisterDefaultResolvers()
    {
        RegisterResolver&lt;RequiredAttribute, SimpleAttributeResolver&gt;(new SimpleAttributeResolver("@Required"));
        RegisterResolver&lt;EmailAttribute, SimpleAttributeResolver&gt;(new SimpleAttributeResolver("@Email"));
        RegisterResolver&lt;RangeAttribute, RangeAttributeResolver&gt;();
    }
    #endregion
}
</pre>
<p>We can provide some default resolvers, based on known validation attributes, e.g.:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Defines a simple attribute resolver.
/// &lt;/summary&gt;
public class SimpleAttributeResolver : IAttributeResolver
{
    #region Fields
    private readonly string Constraint;
    #endregion

    #region Constructor
    /// &lt;summary&gt;
    /// Initialises a new instance of &lt;see cref="SimpleAttributeResolver"/&gt;
    /// &lt;/summary&gt;
    /// &lt;param name="constraint"&gt;The constraint to return.&lt;/param&gt;
    public SimpleAttributeResolver(string constraint)
    {
        if (string.IsNullOrEmpty(constraint))
            throw new ArgumentException("'constraint' cannot be null or empty.");

        Constraint = constraint;
    }
    #endregion

    #region Methods
    /// &lt;summary&gt;
    /// Resolves the specified attribute as a Regula constraint.
    /// &lt;/summary&gt;
    /// &lt;param name="attribute"&gt;The attribute to resolve.&lt;/param&gt;
    /// &lt;returns&gt;The resolved constraint.&lt;/returns&gt;
    public string Resolve(ValidationAttribute attribute)
    {
        return Constraint;
    }
    #endregion
}

/// &lt;summary&gt;
/// Defines a simple attribute resolver.
/// &lt;/summary&gt;
public class RangeAttributeResolver : IAttributeResolver
{
    #region Methods
    /// &lt;summary&gt;
    /// Resolves the specified attribute as a Regula constraint.
    /// &lt;/summary&gt;
    /// &lt;param name="attribute"&gt;The attribute to resolve.&lt;/param&gt;
    /// &lt;returns&gt;The resolved constraint.&lt;/returns&gt;
    public string Resolve(ValidationAttribute attribute)
    {
        var attr = attribute as RangeAttribute;
        if (attr == null)
            throw new InvalidOperationException("RangeAttributeResolver requires an instance of RangeAttribute");

        return string.Format("@Range(min={0}, max={1})", attr.Minimum, attr.Maximum);
    }
    #endregion
}
</pre>
<p>We can also create a custom attribute and map that to a resolver:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Validates a field against an email regular expression.
/// &lt;/summary&gt;
public class EmailAttribute : RegularExpressionAttribute
{
    #region Fields
    private const string RegexPattern = @"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b";
    #endregion

    #region Constructor
    /// &lt;summary&gt;
    /// Initialises a new instance of &lt;see cref="EmailAttribute"/&gt;
    /// &lt;/summary&gt;
    public EmailAttribute() : base(RegexPattern)
    { }
    #endregion
}
</pre>
<h3>Wiring up client-side validation</h3>
<p>To handle our client-side validation, we need some way of appending the Regula html attributes to standard controls. I haven&#8217;t found an easy way of doing this without writing a series of extension methods such as RegulaTextBoxFor(&#8230;) etc.  This is only a first version, so I don&#8217;t really care at the moment&#8230;</p>
<p>Let&#8217;s finish off our implementation of our RegulaAdapter:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Provides an adapter for translating validation attributes to Regula constraints.
/// &lt;/summary&gt;
/// &lt;typeparam name="TModel"&gt;The model type.&lt;/typeparam&gt;
public class RegulaAdapter&lt;T&gt;
{
    #region Fields
    private static readonly IDictionary&lt;Type, IAttributeResolver&gt; Resolvers;
    #endregion

    #region Constructor
    /// &lt;summary&gt;
    /// Statically initialises the &lt;see cref="RegulaAdapter{TModel}"/&gt; type.
    /// &lt;/summary&gt;
    static RegulaAdapter()
    {
        Resolvers = new Dictionary&lt;Type, IAttributeResolver&gt;();
        RegisterDefaultResolvers();
    }

    /// &lt;summary&gt;
    /// Initialises a new instance of &lt;see cref="RegulaAdapter{TModel}"/&gt;
    /// &lt;/summary&gt;
    public RegulaAdapter()
    {
        ModelType = typeof(TModel);
    }
    #endregion

    #region Properties
    /// &lt;summary&gt;
    /// Gets the model type.
    /// &lt;/summary&gt;
    public Type ModelType { get; private set; }
    #endregion

    #region Methods
    /// &lt;summary&gt;
    /// Registers an attribute resolver for the specified attribute.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TAttribute"&gt;The type of attribute.&lt;/typeparam&gt;
    /// &lt;typeparam name="TResolver"&gt;The type of resolver.&lt;/typeparam&gt;
    public static void RegisterResolver&lt;TAttribute, TResolver&gt;()
        where TAttribute : ValidationAttribute
        where TResolver: IAttributeResolver, new()
    {
        RegisterResolver&lt;TAttribute, TResolver&gt;(new TResolver());
    }

    /// &lt;summary&gt;
    /// Registers an attribute resolver for the specified attribute.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TAttribute"&gt;The type of attribute.&lt;/typeparam&gt;
    /// &lt;typeparam name="TResolver"&gt;The type of resolver.&lt;/typeparam&gt;
    /// &lt;param name="resolver"&gt;The instance of resolver to register.&lt;/param&gt;
    public static void RegisterResolver&lt;TAttribute, TResolver&gt;(TResolver resolver)
        where TAttribute : ValidationAttribute
        where TResolver : IAttributeResolver
    {
        var type = typeof(TAttribute);

        if (Resolvers.ContainsKey(type))
            Resolvers[type] = resolver;
        else
            Resolvers.Add(type, resolver);
    }

    /// &lt;summary&gt;
    /// Registers any default resolvers.
    /// &lt;/summary&gt;
    private static void RegisterDefaultResolvers()
    {
        RegisterResolver&lt;RequiredAttribute, SimpleAttributeResolver&gt;(new SimpleAttributeResolver("@Required"));
        RegisterResolver&lt;EmailAttribute, SimpleAttributeResolver&gt;(new SimpleAttributeResolver("@Email"));
        RegisterResolver&lt;RangeAttribute, RangeAttributeResolver&gt;();
    }

    /// &lt;summary&gt;
    /// Gets a dictionary of constraints for the specified type.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;A dictionary of constraints for the specified type.&lt;/returns&gt;
    public IEnumerable&lt;string&gt; GetConstraints(string property = null)
    {
        var constraints = new List&lt;string&gt;();

        var attributes = GetAttributes();
        if (!string.IsNullOrEmpty(property))
            attributes = attributes.Concat(GetAttributes(property));

        foreach (var attr in attributes)
        {
            Type type = attr.GetType();
            if (Resolvers.ContainsKey(type))
            {
                var resolver = Resolvers[type];
                constraints.Add(resolver.Resolve(attr));
            }
        }

        return constraints;
    }

    /// &lt;summary&gt;
    /// Gets the attributes applied to the specified model.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;An enumerable of validation attributes.&lt;/returns&gt;
    private IEnumerable&lt;ValidationAttribute&gt; GetAttributes()
    {
        return ModelType
            .GetCustomAttributes(typeof(ValidationAttribute), true)
            .Cast&lt;ValidationAttribute&gt;();
    }

    /// &lt;summary&gt;
    /// Gets the attributes applied to the specified property.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;An enumerable of validation attributes.&lt;/returns&gt;
    private IEnumerable&lt;ValidationAttribute&gt; GetAttributes(string property)
    {
        return ModelType
            .GetProperty(property)
            .GetCustomAttributes(typeof(ValidationAttribute), true)
            .Cast&lt;ValidationAttribute&gt;();
    }
    #endregion
}
</pre>
<p>With that, we can now add a HtmlHelper extension method that will create our textbox:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Provides html helper extensions used to create html controls with Regula validation.
/// &lt;/summary&gt;
public static class RegulaExtensions
{
    #region Methods
    /// &lt;summary&gt;
    /// Creates a textbox for the specified expression that supports Regula validation.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TModel"&gt;The model type.&lt;/typeparam&gt;
    /// &lt;typeparam name="TProperty"&gt;The property type.&lt;/typeparam&gt;
    /// &lt;param name="htmlHelper"&gt;The html helper used to generate the control.&lt;/param&gt;
    /// &lt;param name="expression"&gt;The expression used to identify the property to create the control for.&lt;/param&gt;
    /// &lt;param name="htmlAttributes"&gt;The collection of html attributes to render to the client.&lt;/param&gt;
    /// &lt;returns&gt;The string representation of the textbox.&lt;/returns&gt;
    public static MvcHtmlString RegulaTextBoxFor&lt;TModel, TProperty&gt;
        (this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, IDictionary&lt;string, object&gt; htmlAttributes)
    {
        if (htmlAttributes == null)
        {
            htmlAttributes = new Dictionary&lt;string, object&gt; { { "class", "regula-validation" } };
        }
        else
        {
            if (htmlAttributes.ContainsKey("class"))
                htmlAttributes["class"] = string.Join(" ", htmlAttributes["class"] as string, "regula-validation");
            else
                htmlAttributes.Add("class", "regula-validation");
        }

        var adapter = new RegulaAdapter&lt;TModel&gt;();
        var member = expression.Body as MemberExpression;
        string name = member == null ? null : member.Member.Name;

        var constraints = adapter.GetConstraints(name);
        htmlAttributes.Add("data-constraints", string.Join(" ", constraints));

        return htmlHelper.TextBoxFor(expression, htmlAttributes);
    }

    /// &lt;summary&gt;
    /// Creates a textbox for the specified expression that supports Regula validation.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TModel"&gt;The model type.&lt;/typeparam&gt;
    /// &lt;typeparam name="TProperty"&gt;The property type.&lt;/typeparam&gt;
    /// &lt;param name="htmlHelper"&gt;The html helper used to generate the control.&lt;/param&gt;
    /// &lt;param name="expression"&gt;The expression used to identify the property to create the control for.&lt;/param&gt;
    /// &lt;param name="htmlAttributes"&gt;The object that represents the collection of html attributes.&lt;/param&gt;
    /// &lt;returns&gt;The string representation of the textbox.&lt;/returns&gt;
    public static MvcHtmlString RegulaTextBoxFor&lt;TModel, TProperty&gt;
        (this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression, object htmlAttributes)
    {
        return RegulaTextBoxFor(htmlHelper, expression, new RouteValueDictionary(htmlAttributes));
    }

    /// &lt;summary&gt;
    /// Creates a textbox for the specified expression that supports Regula validation.
    /// &lt;/summary&gt;
    /// &lt;typeparam name="TModel"&gt;The model type.&lt;/typeparam&gt;
    /// &lt;typeparam name="TProperty"&gt;The property type.&lt;/typeparam&gt;
    /// &lt;param name="htmlHelper"&gt;The html helper used to generate the control.&lt;/param&gt;
    /// &lt;param name="expression"&gt;The expression used to identify the property to create the control for.&lt;/param&gt;
    /// &lt;returns&gt;The string representation of the textbox.&lt;/returns&gt;
    public static MvcHtmlString RegulaTextBoxFor&lt;TModel, TProperty&gt;
        (this HtmlHelper&lt;TModel&gt; htmlHelper, Expression&lt;Func&lt;TModel, TProperty&gt;&gt; expression)
    {
        return RegulaTextBoxFor(htmlHelper, expression, null);
    }
    #endregion
}
</pre>
<h3>Example Model with Client-side Validation</h3>
<p>As an example, we&#8217;ll modify the stock ASP.NET MVC project. Let&#8217;s create an example model:</p>
<pre class="brush: csharp">
public class Person
{
    #region Properties
    [Required]
    public string Name { get; set; }

    [Email]
    public string Email { get; set; }

    [Range(0, 120)]
    public int Age { get; set; }
    #endregion
}
</pre>
<p>By passing a dummy instance to our view, we can express the validation using something similar to:</p>
<pre class="brush: csharp">
&lt;script type="text/javascript" src="/Scripts/jquery-1.4.1.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="/Scripts/Regula.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
    $(function () {
        $.regula("myForm", function (results) {
            console.log(results);
        });
    });
&lt;/script&gt;
&lt;h2&gt;&lt;%: ViewData["Message"] %&gt;&lt;/h2&gt;
&lt;p&gt;
    To learn more about ASP.NET MVC visit &lt;a href="http://asp.net/mvc" title="ASP.NET MVC Website"&gt;http://asp.net/mvc&lt;/a&gt;.
&lt;/p&gt;
&lt;% Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "myForm" }); %&gt;
&lt;p&gt;
    &lt;%= Html.RegulaTextBoxFor(m =&gt; m.Name) %&gt;
&lt;/p&gt;
&lt;p&gt;
    &lt;%= Html.RegulaTextBoxFor(m =&gt; m.Email) %&gt;
&lt;/p&gt;
&lt;p&gt;
    &lt;%= Html.RegulaTextBoxFor(m =&gt; m.Age) %&gt;
&lt;/p&gt;
&lt;input type="submit" value="Submit" /&gt;
&lt;% Html.EndForm(); %&gt;
</pre>
<p>Which should generate the following html markup:</p>
<pre class="brush: html">
&lt;script type="text/javascript" src="/Scripts/jquery-1.4.1.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript" src="/Scripts/Regula.js"&gt;&lt;/script&gt;
&lt;script type="text/javascript"&gt;
    $(function () {
        $.regula("myForm", function (results) {
            console.log(results);
        });
    });
&lt;/script&gt;
&lt;h2&gt;Welcome to ASP.NET MVC!&lt;/h2&gt;
&lt;p&gt;
    To learn more about ASP.NET MVC visit &lt;a href="http://asp.net/mvc" title="ASP.NET MVC Website"&gt;http://asp.net/mvc&lt;/a&gt;.
&lt;/p&gt;

&lt;form action="/" id="myForm" method="post"&gt;
&lt;p&gt;
    &lt;input class="regula-validation" data-constraints="@Required" id="Name" name="Name" type="text" value="" /&gt;
&lt;/p&gt;
&lt;p&gt;
    &lt;input class="regula-validation" data-constraints="@Email" id="Email" name="Email" type="text" value="" /&gt;
&lt;/p&gt;
&lt;p&gt;
    &lt;input class="regula-validation" data-constraints="@Range(min=0, max=120)" id="Age" name="Age" type="text" value="0" /&gt;

&lt;/p&gt;
&lt;input type="submit" value="Submit" /&gt;
&lt;/form&gt;

        &lt;div id="footer"&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/div&gt;
</pre>
<p>As I said, it is possible, and it also makes me wonder if this could be adapted to work with something like xVal? Who knows! Please find the example project attached&#8230;</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2010/08/RegulaMVC.zip'>RegulaMVC</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180&amp;title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180&amp;title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180&amp;title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180&amp;headline=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180&amp;title=Integrating+Regula+with+ASP.NET+MVC+and+DataAnnotations&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D180" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=weCgZSy55lg:a7p6phkST1g:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=weCgZSy55lg:a7p6phkST1g:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=weCgZSy55lg:a7p6phkST1g:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=weCgZSy55lg:a7p6phkST1g:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=weCgZSy55lg:a7p6phkST1g:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=weCgZSy55lg:a7p6phkST1g:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=weCgZSy55lg:a7p6phkST1g:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=weCgZSy55lg:a7p6phkST1g:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/weCgZSy55lg" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=180</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=180</feedburner:origLink></item>
		<item>
		<title>Regula as a jQuery Plugin</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/FOBAQgCRSJo/</link>
		<comments>http://www.fidelitydesign.net/?p=175#comments</comments>
		<pubDate>Fri, 13 Aug 2010 22:00:16 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[JQuery]]></category>
		<category><![CDATA[regula]]></category>
		<category><![CDATA[validation]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=175</guid>
		<description><![CDATA[Earlier this evening I came across a Stack Overflow question regarding a most excellent new javascript validation framework, called Regula.  Regula is an annotation-based validation framework that hides the complexities of binding complex validation events to controls by extending the DOM element itself with annotations about how it should be validated. Here is a [...]]]></description>
			<content:encoded><![CDATA[<p>Earlier this evening I came across a Stack Overflow question regarding a most excellent new javascript validation framework, called <a href="http://vivin.net/2010/03/30/regula-an-annotation-based-form-validator-written-in-javascript/">Regula</a>.  Regula is an annotation-based validation framework that hides the complexities of binding complex validation events to controls by extending the DOM element itself with annotations about how it should be validated. Here is a quick example:</p>
<pre class="brush: javascript">
&lt;input id="emailAddress" type="text" class="regula-validation" data-constaints="@NotEmpty, @Email" /&gt;
</pre>
<p>In the above example, im forcing that textbox to validate against two constraints, a @NotEmpty constraint, and an @Email constraint, both of which are quite self-explanatory.  Although I&#8217;ve only just started looking at it, it does look very promising, offering an array of built-in constraints, as well as the ability to quickly add your own, allowing you to easily reuse constraints on multiple fields across multiple pages.</p>
<p>One thing I quickly wanted to add in though, as a way to use Regula as a jQuery plugin, and thus I added the following to the Regula source:</p>
<pre class="brush: javascript">if (jQuery) {
    (function($)
    {
        $.regula = function(formId, callback) {
            regula.bind();

            $("#" + formId).submit(function() {
                var validationResults = regula.validate();

                if (validationResults.length > 0)
                {
                    if (callback)
                        callback(validationResults);

                    return false;
                }

                return true;
            });
        };
    })(jQuery);
}</pre>
<p>Now we can easily call:</p>
<pre class="brush: javascript">$(function()
{
    $.regula("myForm", function(results)
    {
        // Do something with validation results here.
    });
});
</pre>
<p>This greatly simplifies the binding of the validation controls to the form, and gives us an optional callback for when validation fails.</p>
<p>Please visit <a href="http://vivin.net/">Vivin Paliath&#8217;s blog</a> for more information <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175&amp;title=Regula+as+a+jQuery+Plugin" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175&amp;title=Regula+as+a+jQuery+Plugin" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175&amp;title=Regula+as+a+jQuery+Plugin" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175&amp;headline=Regula+as+a+jQuery+Plugin" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Regula+as+a+jQuery+Plugin&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Regula+as+a+jQuery+Plugin&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Regula+as+a+jQuery+Plugin&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Regula+as+a+jQuery+Plugin&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Regula+as+a+jQuery+Plugin&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175&amp;title=Regula+as+a+jQuery+Plugin&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D175" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=FOBAQgCRSJo:EkigVFq2egs:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=FOBAQgCRSJo:EkigVFq2egs:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=FOBAQgCRSJo:EkigVFq2egs:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=FOBAQgCRSJo:EkigVFq2egs:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=FOBAQgCRSJo:EkigVFq2egs:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=FOBAQgCRSJo:EkigVFq2egs:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=FOBAQgCRSJo:EkigVFq2egs:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=FOBAQgCRSJo:EkigVFq2egs:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/FOBAQgCRSJo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=175</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=175</feedburner:origLink></item>
		<item>
		<title>Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/3Pl4dhm9vws/</link>
		<comments>http://www.fidelitydesign.net/?p=159#comments</comments>
		<pubDate>Fri, 16 Jul 2010 10:20:56 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[autofac]]></category>
		<category><![CDATA[exportattribute]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[metadata]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[refactor]]></category>
		<category><![CDATA[unity]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=159</guid>
		<description><![CDATA[
See also: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
See also: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
Currently reading: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three

Firstly, sorry it&#8217;s been so long since my last MVC+MEF post, been a bit busy with life in general. [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li>See also: <a href="http://www.fidelitydesign.net/?p=104">Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One</a></li>
<li>See also: <a href="http://www.fidelitydesign.net/?p=130">Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two</a></li>
<li>Currently reading: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three</li>
</ul>
<p>Firstly, sorry it&#8217;s been so long since my last MVC+MEF post, been a bit busy with life in general.  Still haven&#8217;t managed to get my project onto CodePlex, but we shall see soon!</p>
<p>Ok, so where did we get to last time? We&#8217;ve managed to build a prototype MVC+MEF framework that supports modular areas and strongly-typed views.  A couple of readers have been asking how we can incorporate IoC into our framework, and the question is really: do we need to?</p>
<p>This framework was originally conceived as a starting point for building a web application, so we could essentially allow MEF do handle our DI for us.  But its not often the case that we can simply start a new project, but build off an existing project, and to go one stage further, if you have a lot of your existing code infrastructure built around an existing IoC container, then you really need to expose that existing infrastructure to your website.</p>
<p>The good news is there is a way, and it&#8217;s rather easy.  <a href="http://blogs.msdn.com/b/gblock/">Glenn Block</a> (everyone&#8217;s favourite MEF guy) pointed me to a rather interesting project, called the Common Services Locator, you can find it on CodePlex <a href="http://commonservicelocator.codeplex.com/">here</a>.</p>
<p>The CSL project is geared to providing a common abstraction over service location (i.e. accessing and instantiating types, regardless of which third-party IoC container you are using).  As long as they provide a CSL provider, we can leverage them relatively easily with out MEF+MVC framework.</p>
<p>So this blog post is essentially going to cover the integration of an IoC container (actually, 2, just to demonstrate how easy it is) into our framework. But before we can do that, we really need to look at refactoring bits of our code.  Let&#8217;s begin with composition.</p>
<h3>Refactoring Composition</h3>
<p>In the previous version of the framework, we had all composition taking place within our Application class. This locks both the CompositionContainer, and its associated Catalogs and ExportProviders, hiding them away from the public.  If you want to leverage composition in another part of your site, it was exactly easy. So, in steps our new Composer class.  This essentially is a wrapper around all the composition functionality of the project, and is something we can easily pass round.  Let&#8217;s have a look:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Provides a common mechanism for composing parts.
/// &lt;/summary&gt;
public class Composer : IComposer
{
  //
}
</pre>
<p>The Composer wraps up the management of the container, as well as adding any catalogs and export providers.  This allows us to easily re-build the catalog as and when we need.  When we want to composer a singular instance, we can easily do:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Composes the specified object.
/// &lt;/summary&gt;
/// &lt;param name="object"&gt;The object to be composed.&lt;/param&gt;
public void Compose(object @object)
{
    if (@object == null)
        throw new ArgumentNullException("object");

    if (Catalog == null)
        return;

    EnsureContainer();
    Container.ComposeParts(@object);
}

/// &lt;summary&gt;
/// Ensures the Container has been instantiated/re-instantiated if the Composer has been modified.
/// &lt;/summary&gt;
private void EnsureContainer()
{
    if (modified || Container == null)
    {
        if (Container != null)
            Container.Dispose();

        Container = new CompositionContainer(Catalog, ExportProviders.ToArray());

        foreach (var provider in postContainerModifiers.Keys)
            postContainerModifiers[provider](provider, Container);

        if (ExportSelf)
        {
            var batch = new CompositionBatch();
            batch.AddExportedValue&lt;IComposer&gt;(this);
            Container.Compose(batch);
        }

        modified = false;
    }
}
</pre>
<p>I&#8217;ve added an interface, IComposer, which provides a contract by which we can export the Composer itself.  This may be useful in scenarios where you want to resolve type instances manually witout worrying about MEF itself.  Because of this, the terminology I&#8217;ve used for the interface is much more akin to an IoC container, so methods like Resolve and ResolveAll are exposed here.  You could then import/inject an instance of the composer if you wanted to:</p>
<pre class="brush: csharp">
[ImportingConstructor]
public MyType(IComposer composer) {
  var instance = composer.Resolve&lt;IMyMagicType&gt;();
}
</pre>
<p>Although really, if you know what types your going to be using, you could just inject them directly instead of using the composer.</p>
<p>We&#8217;ve had to refactor the Application class itself to now support the Composer, luckily this wasn&#8217;t a lot of work:</p>
<pre class="brush: csharp">
#region Properties
/// &lt;summary&gt;
/// Gets the &lt;see cref="Composer" /&gt; used to compose parts.
/// &lt;/summary&gt;
public static Composer Composer { get; private set; }
#endregion

#region Methods
/// &lt;summary&gt;
/// The start method of the application.
/// &lt;/summary&gt;
protected void Application_Start()
{
    // Perform any tasks required before composition.
    PreCompose();

    // Create the composer used for composition.
    Composer = CreateComposer();

    // Compose the application.
    Compose();

    // Set the controller factory.
    ControllerBuilder.Current.SetControllerFactory(ControllerFactory);

    // Set the view engine that supports imported areas.
    ViewEngines.Engines.Add(new AreaViewEngine());

    // Initialises the application.
    Initialise();

    // Register MVC routes.
    RegisterRoutes();
}

/// &lt;summary&gt;
/// Creates a &lt;see cref="Composer" /&gt; used to compose parts.
/// &lt;/summary&gt;
/// &lt;returns&gt;&lt;/returns&gt;
protected virtual Composer CreateComposer()
{
    var composer = new Composer();

    GetDirectoryCatalogs()
        .ForEach(composer.AddCatalog);

    composer.AddExportProvider(
        new DynamicInstantiationExportProvider(),
        (provider, container) =&gt; ((DynamicInstantiationExportProvider)provider).SourceProvider = container);

    return composer;
}
</pre>
<p>We once again make the CreateComposer method virtual, so if you do want exact control of how the Composer is created, possibly to wire up additional export providers/catalogs etc, you can override this and do what you want.</p>
<h3>Refactoring Exports</h3>
<p>Currently we manage our exports through a combination of the ExportAttribute and the ExportMetadataAttribute types.  This is great, its easy, but does lead to problems, particularly when metadata is missing this is required for composition. This is important, as MEF will not compose types which do not satisfy the required import definitions.  Consider our Controller type, currently we see this:</p>
<pre class="brush: csharp">
[Export(typeof(IController)), ExportMetadata("Name", "Blog")]
public BlogController: Controller
{

}
</pre>
<p>If we forget the ExportMetadataAttribute attribute, the controller will not be composed.  What we really need to do, is ensure that the controller metadata is passed with the export.  We can create a custom export attribute which provides this metadata:</p>
<pre class="brush: csharp">
/// &lt;summary&gt;
/// Exports a controller.
/// &lt;/summary&gt;
[MetadataAttribute, AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class ExportControllerAttribute : ExportAttribute, IControllerMetadata
{
    #region Constructor
    /// &lt;summary&gt;
    /// Initialises a new instance of the &lt;see cref="ExportControllerAttribute"/&gt; class.
    /// &lt;/summary&gt;
    /// &lt;param name="name"&gt;The name of the controller.&lt;/param&gt;
    public ExportControllerAttribute(string name) : base(typeof(IController))
    {
        if (string.IsNullOrEmpty(name))
            throw new ArgumentException("Controller name cannot be null or empty.");

        this.Name = name;
    }
    #endregion

    #region Properties
    /// &lt;summary&gt;
    /// Gets the name of the controller.
    /// &lt;/summary&gt;
    public string Name { get; private set; }
    #endregion
}
</pre>
<p>This export attribute ensures that we have the controller name alongside the export.  One thing to note, is you don&#8217;t actually have to decorate this type with your metadata interface, MEF will project the required properties for you, but I like to do so, as I know it ensures that my export attribute is conforming to my required metadata interface.</p>
<p>Now, we can simply our export:</p>
<pre class="brush: csharp">
[ExportController("Blog")]
public BlogController: Controller
{

}
</pre>
<h3>Integrating Unity into MEF+MVC</h3>
<p>Ok, finally onto what we really want to do, IoC integration <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . To add support for Unity (and any compatible CSL provider, I&#8217;ve added a bit of code supplied by Mr. Block, the CSLExportProvider (read: <a href="http://codepaste.net/s6w6az">Glenn&#8217;s code</a>).  We can augment this ExportProvider into our Composer, and then wire up our Unity container:</p>
<pre class="brush: csharp">
public class MvcApplication : Application
{
    #region Fields
    private IUnityContainer unityContainer;
    private CSLExportProvider exportProvider;
    #endregion

    #region Methods
    /// &lt;summary&gt;
    /// Creates the instance of the Unity container.
    /// &lt;/summary&gt;
    protected override void PreCompose()
    {
        unityContainer = new UnityContainer();

        var locator = new UnityServiceLocator(unityContainer);
        exportProvider = new CSLExportProvider(locator);

        unityContainer.AddExtension(new CSLExportProviderExtension(exportProvider));

        RegisterTypes();
    }

    /// &lt;summary&gt;
    /// Registers any required types for the Unity container.
    /// &lt;/summary&gt;
    protected void RegisterTypes()
    {
        unityContainer.RegisterType&lt;ITicketSystem, SimpleTicketSystem&gt;();
    }

    /// &lt;summary&gt;
    /// Creates the composer used for composition.
    /// &lt;/summary&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    protected override MefMvcFramework.Composition.Composer CreateComposer()
    {
        var composer = base.CreateComposer();
        composer.AddExportProvider(exportProvider);

        return composer;
    }
    #endregion
}
</pre>
<p>In the example above, we are taking advantage of our Application class design to control how the Composer is constructed in relation to our IoC Container, Unity. We are then registering a simple example type, the ITicketSystem.  Because we&#8217;ve registered this type with Unity, thanks to the Common Services Locator provider, we can now access these when importing/injecting into our target types. Let&#8217;s create a new MVC Controller to demonstrate this:
</p>
<pre class="brush: csharp">
[ExportController("Support")]
public class SupportController : Controller
{
    #region Fields
    private ITicketSystem ticketSystem;
    #endregion

    #region Constructor
    [ImportingConstructor]
    public SupportController(ITicketSystem ticketSystem)
    {
        this.ticketSystem = ticketSystem;
    }
    #endregion

    #region Actions
    public ActionResult Index()
    {
        var ticket = ticketSystem.CreateTicket();
        return Content(ticket.Title);
    }
    #endregion
}
</pre>
<p>With our new controller, when we create an instance, we inject our ITicketSystem instance through the constructor.  The important thing here, is that our instance of ITicketSystem is provided by our IoC container (currently Unity), exposed via MEF.  Thus demonstrates just how flexible and robust MEF really is.</p>
<p>We can even do it for another IoC container, let&#8217;s try Autofac:</p>
<pre class="brush: csharp">
public class MvcApplication : Application
{
  #region Fields
  private CSLExportProvider exportProvider;
  #endregion

  #region Methods
  /// &lt;summary&gt;
  /// Creates the instance of the Unity container.
  /// &lt;/summary&gt;
  protected override void PreCompose()
  {
      var container = new ContainerBuilder().Build();
      exportProvider = new CSLExportProvider(new AutofacServiceLocator(container));

      RegisterTypes(container);
  }

  /// &lt;summary&gt;
  /// Registers any types required for the container.
  /// &lt;/summary&gt;
  /// &lt;param name="container"&gt;The container.&lt;/param&gt;
  private void RegisterTypes(IContainer container)
  {
      var builder = new ContainerBuilder();

      builder.RegisterType&lt;SimpleTicketSystem&gt;().As&lt;ITicketSystem&gt;();
      exportProvider.RegisterType(typeof(ITicketSystem));

      builder.Update(container);
  }

  /// &lt;summary&gt;
  /// Creates the composer used for composition.
  /// &lt;/summary&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  protected override MefMvcFramework.Composition.Composer CreateComposer()
  {
      var composer = base.CreateComposer();
      composer.AddExportProvider(exportProvider);

      return composer;
  }
  #endregion
}
</pre>
<p>Minimal code change makes me very happy! Any CSL compatible provider can be used, allowing enormous flexibility and integration options. Hope you like it!</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2010/07/MefMvcFrameworkWithUnity.zip'>Download VS2010 Project</a></p>
<p><strong>UPDATE</strong> For Martyn: wiring up Castle Windsor was really easy, in fact took my only a few minutes to wire it up and add a component to the container.  This is again thanks to the CSL project, whereby you can grab a CSL-provider for Castle Windsor.</p>
<p>The code change is as follows:</p>
<pre class="brush: csharp">
namespace MefMvcApplication
{
    using Castle.Windsor;
    using CommonServiceLocator.WindsorAdapter;

    using MefMvcFramework.Example.TicketSystem;
    using MefMvcFramework.ServiceLocation;
    using MefMvcFramework.Web;

    public class MvcApplication : Application
    {
        #region Fields
        private CSLExportProvider exportProvider;
        #endregion

        #region Methods
        /// &lt;summary&gt;
        /// Creates the instance of the Unity container.
        /// &lt;/summary&gt;
        protected override void PreCompose()
        {
            var container = new WindsorContainer();
            exportProvider = new CSLExportProvider(new WindsorServiceLocator(container));

            RegisterTypes(container);
        }

        /// &lt;summary&gt;
        /// Registers any types required for the container.
        /// &lt;/summary&gt;
        /// &lt;param name="container"&gt;The container.&lt;/param&gt;
        private void RegisterTypes(IWindsorContainer container)
        {
            container.AddComponent("TicketSystem", typeof(ITicketSystem), typeof(SimpleTicketSystem));
            exportProvider.RegisterType(typeof(ITicketSystem));
        }

        /// &lt;summary&gt;
        /// Creates the composer used for composition.
        /// &lt;/summary&gt;
        /// &lt;returns&gt;&lt;/returns&gt;
        protected override MefMvcFramework.Composition.Composer CreateComposer()
        {
            var composer = base.CreateComposer();
            composer.AddExportProvider(exportProvider);

            return composer;
        }
        #endregion
    }
}
</pre>
<p>The Castle Windsor variant of the project is attached.  Hope that helps.</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2010/07/MefMvcAndCastleWindsor.zip'>Download VS 2010 Project (Castle Windsor)</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159&amp;headline=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Three&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D159" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=3Pl4dhm9vws:vMB6HAE-sr4:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=3Pl4dhm9vws:vMB6HAE-sr4:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=3Pl4dhm9vws:vMB6HAE-sr4:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=3Pl4dhm9vws:vMB6HAE-sr4:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=3Pl4dhm9vws:vMB6HAE-sr4:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=3Pl4dhm9vws:vMB6HAE-sr4:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=3Pl4dhm9vws:vMB6HAE-sr4:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=3Pl4dhm9vws:vMB6HAE-sr4:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/3Pl4dhm9vws" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=159</wfw:commentRss>
		<slash:comments>4</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=159</feedburner:origLink></item>
		<item>
		<title>Javascript Linq Extensions</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/Yw_Uz1P2Zoo/</link>
		<comments>http://www.fidelitydesign.net/?p=149#comments</comments>
		<pubDate>Fri, 25 Jun 2010 08:49:42 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[linq]]></category>
		<category><![CDATA[unit-testing]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=149</guid>
		<description><![CDATA[I love Linq. Linq just makes code awesome.  Well, that&#8217;s my view on it anyway. I also like Javascript, and through libraries like JQuery we&#8217;ve now got a framework whereby you can pretty much do anything, but often I like getting down to the bare-bones of Javascript and just having a go at what [...]]]></description>
			<content:encoded><![CDATA[<p>I love Linq. Linq just makes code awesome.  Well, that&#8217;s my view on it anyway. I also like Javascript, and through libraries like JQuery we&#8217;ve now got a framework whereby you can pretty much do anything, but often I like getting down to the bare-bones of Javascript and just having a go at what it can do.</p>
<p>One of the great things about Javascript objects is that they are so easy to extend.  This is due to the prototyping nature of the language itself.  Recently on my journey on Stack Overflow (~1200 in 22 days!) a question was asked about searching through a javascript array for a specific item.  Of course we could easily do something like this:</p>
<pre class="brush: javascript">
for (var i = 0; i < arrayObj.length; i++) { ... }
</pre>
<p>...etc, but I remembered a while ago I had written some very cool Linq-esque style extension methods to Javascript array object.  Methods like Where, Select, etc, here's an example of my Where method:</p>
<pre class="brush: javascript">
Array.prototype.Where = function(predicate) {
    Throw.IfArgumentNull(predicate, "predicate");
    Throw.IfNotAFunction(predicate, "predicate");

    var results = new Array();
    for (var i = 0; i < this.length; i++) {
        var item = this[i];
        if (predicate(item))
            results.push(item);
    }

    return results;
};
</pre>
<p>Given that, I could do something like so:</p>
<pre class="brush: javascript">
  Person = function(name, age, likes) {
    this.Name = name;
    this.Age = age;
    this.Likes = likes;
  };

  var people = [
    new Person("Doug", 20, "Bananas"),
    new Person("Jeff", 21, "Apples"),
    new Person("Richard", 22, "Oranges"),
    new Person("Bonzo", 50, "Bananas")
  ];

  var peopleWhoLikeBananas = people.Where(function(p) {
    return (p.Likes == "Bananas"); });
</pre>
<p>Pretty cool eh? If you're familiar with the Linq extension methods, you should be at home here too!</p>
<p>I also decided to extend the base Object class itself, providing some Equals and CompareTo methods that act as default equality and comparer methods:</p>
<pre class="brush: javascript">
Object.Equals = function(objA, objB) {
    if (objA != null)
        return objA.Equals(objB);

    if (objB != null)
        return objB.Equals(objA);

    return false;
};

Object.prototype.CompareTo = function(object) {
    if (this < object)
        return -1;

    if (this > object)
        return 1;

    return 0;
};

Object.prototype.Equals = function(object) {
    return (this == object);
};
</pre>
<p>Also included in the attached zip is my prototype Javascript testing framework and also the micro-mocking framework I <a href="http://www.fidelitydesign.net/?p=95">blogged about previously</a>, it's nothing special and nowhere near production code:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Firebug-Testing.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Firebug-Testing-300x182.jpg" alt="" title="Firebug-Testing" width="300" height="182" class="alignnone size-medium wp-image-152" /></a></p>
<p>Attached in a zip of all the bits and bobs, its nothing formal and it's not production code, do with it what you will.  I appreciate any feedback too.</p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2010/06/Javascript-Linq-Extensions.zip'>Javascript-Linq-Extensions</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149&amp;title=Javascript+Linq+Extensions" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149&amp;title=Javascript+Linq+Extensions" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149&amp;title=Javascript+Linq+Extensions" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149&amp;headline=Javascript+Linq+Extensions" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Javascript+Linq+Extensions&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Javascript+Linq+Extensions&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Javascript+Linq+Extensions&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Javascript+Linq+Extensions&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Javascript+Linq+Extensions&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149&amp;title=Javascript+Linq+Extensions&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D149" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yw_Uz1P2Zoo:HBXiSUPf2M8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yw_Uz1P2Zoo:HBXiSUPf2M8:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Yw_Uz1P2Zoo:HBXiSUPf2M8:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yw_Uz1P2Zoo:HBXiSUPf2M8:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Yw_Uz1P2Zoo:HBXiSUPf2M8:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yw_Uz1P2Zoo:HBXiSUPf2M8:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yw_Uz1P2Zoo:HBXiSUPf2M8:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Yw_Uz1P2Zoo:HBXiSUPf2M8:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/Yw_Uz1P2Zoo" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=149</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=149</feedburner:origLink></item>
		<item>
		<title>Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/Yba1Fwu-auA/</link>
		<comments>http://www.fidelitydesign.net/?p=130#comments</comments>
		<pubDate>Mon, 07 Jun 2010 13:24:25 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[strongly-typed-models]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=130</guid>
		<description><![CDATA[
See also: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One
Currently reading: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two
See also: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three

In my previous post I presented an MVC Framework that uses the Managed Extensibility Framework (MEF) to allow for [...]]]></description>
			<content:encoded><![CDATA[<ul>
<li>See also: <a href="http://www.fidelitydesign.net/?p=104">Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One</a>
<li>Currently reading: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two</li>
<li>See also: <a href="http://www.fidelitydesign.net/?p=159">Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three</a>
</ul>
<p>In my previous post I presented an MVC Framework that uses the Managed Extensibility Framework (MEF) to allow for powerful extensibility of ASP.NET MVC, not just for controllers, but also for views. <a href="http://www.fidelitydesign.net/?p=104">You can find my original article here</a>.</p>
<p>There are a couple of small issues I want to iron out before it becomes a project-quality framework. These issues are:</p>
<ol>
<li>Strongly-typed Models from imported libraries</li>
<li>Managing referenced libraries in built modules</li>
</ol>
<h3>Strongly-typed Models from imported libraries</h3>
<p>In the previous version of the framework, one thing which I had neglected to highlight and test is using a strongly-typed view model from an external module.  This action turned out to be a bigger issue than simply trying to find a reference. The first exception that was thrown at me was this:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/ViewModel-ConfigError.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/ViewModel-ConfigError-300x146.jpg" alt="" title="ViewModel-ConfigError" width="300" height="146" class="alignnone size-medium wp-image-135" /></a></p>
<p>This is quite a common occurence, and is due to the MVC framework not being able to instantiate the types required to process the views.  Because our views sit outside the the /Views folder, the /Views specific configuration items were missing from the config.  We can easily add these in to our main web.config file:</p>
<pre class="brush: xml">
  &lt;system.web&gt;
    &lt;pages
      pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"&gt;
    &lt;/pages&gt;
  &lt;/system.web&gt;
</pre>
<p>Ok, thats done, what next:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/ViewModel-Reference.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/ViewModel-Reference-300x146.jpg" alt="" title="ViewModel-Reference" width="300" height="146" class="alignnone size-medium wp-image-136" /></a></p>
<p>This one was a little more confusing, it can&#8217;t find my type? How comes my Controller can but my View can&#8217;t? In current WebForms technology (including ASP.NET WebForms) our pages are compiled into a seperate assembly, referenced to the main website.  Because we&#8217;ve imported our types using MEF, we haven&#8217;t created a reference to the specific assemblies, so no reference is created to the page assemblies which are generated.  There is another issue here also, our imported assemblies don&#8217;t sit in the /bin folder of the application, so discovering the correct assemblies requires a little work.  Firstly, we need to modify our Application class, changing it&#8217;s CreateCompositionContainer method to fire a call to another method which registers our path for probing.</p>
<pre class="brush: csharp">
  /// &lt;summary&gt;
  /// Creates the composition container.
  /// &lt;/summary&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  protected virtual CompositionContainer CreateCompositionContainer()
  {
      var catalog = new AggregateCatalog();
      catalog.Catalogs.Add(new DirectoryCatalog(MapPath("~/bin")));

      var config = CompositionConfigurationSection.GetInstance();
      if (config != null &#038;&#038; config.Catalogs != null) {
          config.Catalogs
              .Cast&lt;CatalogConfigurationElement&gt;()
              .ForEach(c =&gt;
              {
                  if (!string.IsNullOrEmpty(c.Path)) {
                      string path = c.Path;
                      if (path.StartsWith("~"))
                          path = MapPath(path);

                      foreach (var directoryCatalog in GetDirectoryCatalogs(path)) {

                          // Register our path for probing.
                          RegisterPath(directoryCatalog.FullPath);

                          // Add the catalog.
                          catalog.Catalogs.Add(directoryCatalog);
                      }
                  }
              });
      }

      var provider = new DynamicInstantiationExportProvider();
      var container = new CompositionContainer(catalog, provider);
      provider.SourceProvider = container;

      return container;
  }
</pre>
<p>Here is our method, RegisterPath:</p>
<pre class="brush: csharp">
  /// &lt;summary&gt;
  /// Registers the specified path for probing.
  /// &lt;/summary&gt;
  /// &lt;param name="path"&gt;The probable path.&lt;/param&gt;
  private void RegisterPath(string path)
  {
      AppDomain.CurrentDomain.AppendPrivatePath(path);
  }
</pre>
<p>Ok, it&#8217;s not much, but what it is doing is appending each path for our DirectoryCatalog instances into the private path of the AppDomain. Through the type resolution process, the AppDomain will probe the private paths to try and find the required types, if its not GAC&#8217;d or previously found.</p>
<p>We&#8217;re nearly there, but now we need to make a final change to our views. We need to add in a command to the top of each view, pointing to the assembly which should be referenced for the view. In this example, I&#8217;ve added the MefMvcFramework.Blog assembly as the referenced one:</p>
<pre class="brush: html">
  &lt;%@ Assembly Name="MefMvcFramework.Blog" %&gt;
  &lt;%@ Import Namespace="MefMvcFramework.Blog.Models" %&gt;
  &lt;%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage&lt;Post&gt;" %&gt;
  &lt;asp:Content ContentPlaceHolderID="MainContent" runat="server"&gt;
      &lt;h2&gt;&lt;%: Model.Title %&gt;&lt;/h2&gt;
  &lt;/asp:Content&gt;
</pre>
<p>Let&#8217;s run that, and it now works <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/ViewModel-Corrected.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/ViewModel-Corrected-300x162.jpg" alt="" title="ViewModel-Corrected" width="300" height="162" class="alignnone size-medium wp-image-137" /></a></p>
<h3>Managing referenced libraries in built modules</h3>
<p>It&#8217;s been noted that when we build a module that has references of it&#8217;s own, the default build action for references is to copy any non-GAC&#8217;d references to the output directory of the application.  Commonly with shared functionality you&#8217;d put your support assemblies in the /bin folder and our modules will still be able to run correctly.  For these shared assemblies, we can tell Visual Studio not to deploy them alongside our built modules, we do this by changing the CopyLocal properties of referenced assemblies.</p>
<p>In Visual Studio, select the reference in the solution explorer \References\, and select Properties with the context menu (or press F4):</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Reference-Properties.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Reference-Properties.jpg" alt="" title="Reference-Properties" width="490" height="214" class="alignnone size-full wp-image-138" /></a></p>
<p>Set the CopyLocal property to false, this will stop Visual Studio from deploying the referenced assemblies.</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Reference-CopyLocal.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Reference-CopyLocal.jpg" alt="" title="Reference-CopyLocal" width="331" height="163" class="alignnone size-full wp-image-139" /></a></p>
<p>To see the effect, empty the /Areas/Blog folder of your main application, and rebuild, you should see a much cleaner number of files:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Reference-Output.jpg"><img src="http://www.fidelitydesign.net/wp-content/uploads/2010/06/Reference-Output.jpg" alt="" title="Reference-Output" width="680" height="345" class="alignnone size-full wp-image-140" /></a></p>
<p>What&#8217;s next? I&#8217;d like to investigate dependency injection for Controllers, either through MEF alone, or possibly mixing it up with an IoC container, if required.  Watch this space <img src='http://www.fidelitydesign.net/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href='http://www.fidelitydesign.net/wp-content/uploads/2010/06/RevisedMVCwithMEF-V21.zip'>Download VS2010 Project (fixed)</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130&amp;headline=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+Two&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D130" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yba1Fwu-auA:39SES841cxA:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yba1Fwu-auA:39SES841cxA:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Yba1Fwu-auA:39SES841cxA:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yba1Fwu-auA:39SES841cxA:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Yba1Fwu-auA:39SES841cxA:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yba1Fwu-auA:39SES841cxA:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Yba1Fwu-auA:39SES841cxA:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Yba1Fwu-auA:39SES841cxA:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/Yba1Fwu-auA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=130</wfw:commentRss>
		<slash:comments>3</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=130</feedburner:origLink></item>
		<item>
		<title>Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/vSlkncOu7o8/</link>
		<comments>http://www.fidelitydesign.net/?p=104#comments</comments>
		<pubDate>Thu, 06 May 2010 17:12:28 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[modular]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=104</guid>
		<description><![CDATA[Building on my previous MEF + MVC example, I present a revised framework for building truly modular ASP.NET MVC websites through MEF.]]></description>
			<content:encoded><![CDATA[<ul>
<li>Currently reading: Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part One</li>
<li>See also: <a href="http://www.fidelitydesign.net/?p=130">Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Two</a>
<li>See also: <a href="http://www.fidelitydesign.net/?p=159">Modular ASP.NET MVC using the Managed Extensibility Framework (MEF), Part Three</a>
</ul>
<p>Building on the work I have done previous (see <a href="http://www.fidelitydesign.net/?p=88">Using MEF with MVC Controllers</a>), I&#8217;ve created a revised architecture of MEF + MVC using .NET 4.0.  I&#8217;m (mostly) happy with the outcome.</p>
<p>One of the things I wanted to get right, was allowing true modularity using MEF. As you already know, its now relatively painless to do modular code with ASP.NET (thanks to standard .NET activation, or using something like MEF for automatic composition), but one of the challenges is not how the code plugs in, but the views themselves.  This was always difficult with WebForms because of the way the .aspx pages are compiled (seperately from the code).  The other pain is the way you may have had to organise your files in the file system, they were also disconnected from the libraries because these had to exist in the \bin directory of your application.</p>
<p>Extensible MVC with MEF can address these:</p>
<p>a) Libraries used with MEF catalogs can be in any directory accessible by the application, and<br />
b) Routes do not use filenames, so the location of your .aspx views doesn&#8217;t matter (as long as MVC can access them).</p>
<p>So, how do we go about making a truly modular MVC implementation?  We start with what something similar to before, so lets build a base implementation.  This has evolved a bit since my early version, namely the application work is now in a seperate assembly, MefMvcFramework.</p>
<pre class="brush: csharp">public class Application : HttpApplication {</pre>
<p>Within this application, we declare our two imports:</p>
<pre class="brush: csharp">  [ImportMany] private IEnumerable&lt;Lazy&lt;IRouteRegistrar, IRouteRegistrarMetadata&gt;&gt; RouteRegistrars;
  [Import] private ImportControllerFactory ControllerFactory;</pre>
<p>Our IRouteRegistrar instances allow us to dynamically register our routes, and our ImportControllerFactory handles the creation of controller instances used by MVC.  I&#8217;ve switched to using Lazy&lt;,&gt; for the registrars as we don&#8217;t really need to use a PartFactory&lt;,&gt; (read: PartCreator&lt;,&gt;) instance to manage the dynamic instantiation of instances, there is no need for it, Lazy&lt;,&gt; allows us to access our metadata without the overhead of dynamic instantiation.  Also, PartFactory&lt;,&gt; is geared to creating new instances, whereas Lazy&lt;,&gt; persists a single instance, using lazy loading.</p>
<p>Next, let&#8217;s flesh out our Application_Start() method:</p>
<pre class="brush: csharp">  protected void Application_Start()
  {
      // Perform any tasks required before composition.
      PreCompose();

      // Compose the application.
      Compose();

      // Set the controller factory.
      ControllerBuilder.Current.SetControllerFactory(ControllerFactory);

      // Set the view engine that supports imported areas.
      ViewEngines.Engines.Add(new AreaViewEngine());

      // Initialises the application.
      Initialise();

      // Register MVC routes.
      RegisterRoutes();
  }</pre>
<p>I&#8217;ve added additional extension points to the application start method as it allows us finer control over how our application is being initialised in relation to composition.  PreCompose(), Compose(), Initialise() and RegisterRoutes() are virtual methods, so we can optional override them in our specific implementation.  They&#8217;re all pretty self-explanitory, so I won&#8217;t go through what each of them does.</p>
<p>What you will notice though, is that I&#8217;ve added a custom ViewEngine.  This is to allow us to use custom locations for our views. I haven&#8217;t built anything particularly special, we just override the view location formats in the constructor:</p>
<pre class="brush: csharp">public class AreaViewEngine : WebFormViewEngine
{
    #region Constructor
    /// &lt;summary&gt;
    /// Initialises a new instance of &lt;see cref="AreaViewEngine" /&gt;.
    /// &lt;/summary&gt;
    public AreaViewEngine()
    {
        MasterLocationFormats = new[]
                                {
                                    "~/Areas/{1}/Views/{0}.master",
                                    "~/Views/{1}/{0}.master",
                                    "~/Views/Shared/{0}.master"
                                };

        ViewLocationFormats = new[]
                                {
                                    "~/Areas/{1}/Views/{0}.aspx",
                                    "~/Views/{1}/{0}.aspx",
                                    "~/Views/Shared/{0}.aspx"
                                };

        AreaPartialViewLocationFormats = new[]
                                {
                                    "~/Areas/{1}/Views/{0}.ascx",
                                    "~/Views/{1}/{0}.ascx",
                                    "~/Views/Shared/{0}.ascx"
                                };
    }
    #endregion
}</pre>
<p>With this view engine, I&#8217;m instructing MVC to look in \Areas for our view content, or more specifically \Areas\&lt;&lt;controller-name&gt;&gt;\ for the content, i.e, if I created a BlogController, it can now look in \Areas\Blog\ for views as well as the standard views.</p>
<p>My project structure now looks as such:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/Pre-AreaSolution.png"><img class="size-full wp-image-107" title="Project Structure" src="http://www.fidelitydesign.net/wp-content/uploads/2010/05/Pre-AreaSolution.png" alt="" width="313" height="589" /></a></p>
<p>I haven&#8217;t done anything specific to the ASP.NET MVC 2 Application project yet, I&#8217;ve simply added a required Areas folder (make sure you do this!), and changed our global application class, it&#8217;s now much leaner:</p>
<pre class="brush: csharp">using MefMvcFramework.Web;

public class MvcApplication : Application
{
    #region Methods
    /// &lt;summary&gt;
    /// Initialises the application.
    /// &lt;/summary&gt;
    protected override void Initialise()
    {

    }
    #endregion
}</pre>
<p>I like that. Because the application class is seperate, we can re-use it in multiple web projects, with minimal implementation in the specific web projects that use it.  You&#8217;ll notice there is no default route registration, thats because we now take advantage of MEF with our application, we make an instance of IRouteRegistrar for our default routes:</p>
<pre class="brush: csharp">[Export(typeof(IRouteRegistrar)), ExportMetadata("Order", 100)]
public class DefaultRouteRegistrar : IRouteRegistrar
{
    #region Methods
    /// &lt;summary&gt;
    /// Registers any routes to be ignored by the routing system.
    /// &lt;/summary&gt;
    /// &lt;param name="routes"&gt;The collection of routes to add to.&lt;/param&gt;
    public void RegisterIgnoreRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.IgnoreRoute("{resource}.ico/{*pathInfo}");
    }

    /// &lt;summary&gt;
    /// Registers any routes to be used by the routing system.
    /// &lt;/summary&gt;
    /// &lt;param name="routes"&gt;The collection of routes to add to.&lt;/param&gt;
    public void RegisterRoutes(RouteCollection routes)
    {
        routes.MapRoute("Default", "{controller}/{action}", new { controller = "Home", action = "Index" });
    }
    #endregion
}</pre>
<p>If you ensure that is done, we should be able to run the application and get our (now familiar) bland ASP.NET MVC example site.  Next though, it&#8217;s time to add a new area.  We going to do this by adding a new project to the solution, and changing some specifics of how it is building/outputting files.  Although this won&#8217;t matter for production (you&#8217;ll hopefully have a much finer control of the build process), it does show how we can easily drop in a new module without having to recompile the main website.  I&#8217;ve created a solution folder \Areas and added a new project, MefMvcFramework.Blog with a few files, here is my new project structure:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/Post-AreaSolution.png"><img class="alignnone size-full wp-image-110" title="Project Structure (Updated)" src="http://www.fidelitydesign.net/wp-content/uploads/2010/05/Post-AreaSolution.png" alt="" width="276" height="265" /></a></p>
<p>What we want, is to change the output location of the project to be in the areas folder of the main website, so open up the project properties, selet the Build tab and change the output path (do this for All Configurations, not just Debug), and change the output to be the \Areas\Blog folder of the main website.</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChangeBuildLocation.png"><img class="alignnone size-thumbnail wp-image-111" title="Changing the Build Location" src="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChangeBuildLocation-150x150.png" alt="" width="150" height="150" /></a></p>
<p>We also need to instruct the views to be copied to the output, so select any views, and goto the Properties window, and change the Copy to Output property to Copy if newer. This means when we build the application, the Index.aspx view should end up at \Areas\Blog\Views\Index.aspx.</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChangeOutputProperty.png"><img class="alignnone size-full wp-image-112" title="Changing the View Output Instruction" src="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChangeOutputProperty.png" alt="" width="297" height="209" /></a></p>
<p>Right then, on to the controller, it&#8217;s not doing anything fancy, just showing us the default view:</p>
<pre class="brush: csharp">[Export(typeof(IController)), ExportMetadata("Name", "Blog")]
public class BlogController : Controller
{
    #region Actions
    /// &lt;summary&gt;
    /// Displays the blog index.
    /// &lt;/summary&gt;
    public ActionResult Index()
    {
        return View();
    }
    #endregion
}</pre>
<p>Hopefully, building the solution and running should demonstrate that the BlogController has been loaded dynamically though MEF and is handling any requests for route /Blog.  If you run this url, you should see something like:</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChromeBlog.png"><img class="alignnone size-full wp-image-113" title="MEF Powered ASP.NET MVC!" src="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChromeBlog.png" alt="" width="673" height="429" /></a></p>
<p>That&#8217;s awesome, we now have a completely modular framework for ASP.NET MVC thanks to MEF. But wait, I want to go one step further.  What I want to achieve is automatically adding a blog link to the navigation.  Now we shouldn&#8217;t hard code this in the page, because the Blog module might not be available. What we can do is add it through the concept of verbs.  So I&#8217;ve created an interface:</p>
<pre class="brush: csharp">public interface IActionVerb
{
    #region Properties
    /// &lt;summary&gt;
    /// Gets the name of the verb.
    /// &lt;/summary&gt;
    string Name { get; }

    /// &lt;summary&gt;
    /// Gets the action.
    /// &lt;/summary&gt;
    string Action { get; }

    /// &lt;summary&gt;
    /// Gets the controller.
    /// &lt;/summary&gt;
    string Controller { get; }
    #endregion
}</pre>
<p>Now, what I&#8217;m going to do with that, is allow MEF to automatically import verbs, and we can then grab them based on category, so here is a sample verb I&#8217;ve added for the Blog:</p>
<pre class="brush: csharp">[Export(typeof(IActionVerb)), ExportMetadata("Category", "Navigation")]
public class BlogVerb : IActionVerb
{
    #region Properties
    /// &lt;summary&gt;
    /// Gets the name.
    /// &lt;/summary&gt;
    public string Name
    {
        get { return "My Blog"; }
    } 

    /// &lt;summary&gt;
    /// Gets the action.
    /// &lt;/summary&gt;
    public string Action
    {
        get { return "Index"; }
    }

    /// &lt;summary&gt;
    /// Gets the controller.
    /// &lt;/summary&gt;
    public string Controller
    {
        get { return "Blog"; }
    }
    #endregion
}</pre>
<p>We&#8217;re going to be mapping verbs to actions on controllers, so let&#8217;s make some changes to our application class, by adding a static field:</p>
<pre class="brush: csharp">  private static IEnumerable&lt;Lazy&lt;IActionVerb, IActionVerbMetadata&gt;&gt; ActionVerbs;</pre>
<p>Now, MEF can&#8217;t compose static instances, and unfortunately we can&#8217;t rely on an instance member either, as an instance of the application class is created with each request (but the Application_Start() method is only executed once for the lifetime of the web application).  So what do we do?  We create the static field, but don&#8217;t mark it as an import, instead, we can manually assign to this field during composition:</p>
<pre class="brush: csharp">  protected virtual void Compose()
  {
      var container = CreateCompositionContainer();
      if (container == null)
          return;

      container.ComposeParts(this);
      ActionVerbs = container.GetExports&lt;IActionVerb, IActionVerbMetadata&gt;();
  }</pre>
<p>Thats the important part done, now lets modify the default view files to support this, firstly, let&#8217;s change our MasterPage:</p>
<pre class="brush: html">  &lt;%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %&gt;

  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head runat="server"&gt;
      &lt;title&gt;&lt;asp:ContentPlaceHolder ID="TitleContent" runat="server" /&gt;&lt;/title&gt;
      &lt;link href="../../Content/Site.css" rel="stylesheet" type="text/css" /&gt;
  &lt;/head&gt;

  &lt;body&gt;
      &lt;div class="page"&gt;

          &lt;div id="header"&gt;
              &lt;div id="title"&gt;
                  &lt;h1&gt;My MVC Application&lt;/h1&gt;
              &lt;/div&gt;

              &lt;div id="logindisplay"&gt;
                  &lt;% Html.RenderPartial("LogOnUserControl"); %&gt;
              &lt;/div&gt; 

              &lt;% Html.RenderPartial("NavigationItems"); %&gt;
          &lt;/div&gt;

          &lt;div id="main"&gt;
              &lt;asp:ContentPlaceHolder ID="MainContent" runat="server" /&gt;

              &lt;div id="footer"&gt;
              &lt;/div&gt;
          &lt;/div&gt;
      &lt;/div&gt;
  &lt;/body&gt;
  &lt;/html&gt;</pre>
<p>I&#8217;ve taken out the original menu, and added a RenderPartial instruction, which accepts our NavigationItems.ascx view, which we&#8217;ll go ahead and create now:</p>
<pre class="brush: csharp">  &lt;%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %&gt;
  &lt;%@ Import Namespace="MefMvcApplication" %&gt;
  &lt;div id="menucontainer"&gt;

      &lt;ul id="menu"&gt;
          &lt;li&gt;&lt;%: Html.ActionLink("Home", "Index", "Home")%&gt;&lt;/li&gt;
          &lt;li&gt;&lt;%: Html.ActionLink("About", "About", "Home")%&gt;&lt;/li&gt;
          &lt;% foreach (var verb in MvcApplication.GetVerbsForCategory("Navigation")) { %&gt;
              &lt;li&gt;&lt;%: Html.ActionLink(verb.Name, verb.Action, verb.Controller)%&gt;&lt;/li&gt;
          &lt;% } %&gt;
      &lt;/ul&gt;

  &lt;/div&gt;</pre>
<p>But how do we get to our verbs? We need to add another method to our application class, GetVerbsForCategory(string):</p>
<pre class="brush: csharp">  public static IEnumerable&lt;IActionVerb&gt; GetVerbsForCategory(string category)
  {
      Throw.IfArgumentNullOrEmpty(category, "category");

      return ActionVerbs
          .Where(l =&gt; l.Metadata.Category.Equals(category, StringComparison.InvariantCultureIgnoreCase))
          .Select(l =&gt; l.Value);
  }</pre>
<p>And that should be it! Run the application again, you should see a My Blog link in the navigation, all handled dynamically!</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChromeBlogWithVerb.png"><img class="alignnone size-full wp-image-114" title="Dynamic Navigation through Verbs" src="http://www.fidelitydesign.net/wp-content/uploads/2010/05/ChromeBlogWithVerb.png" alt="" width="678" height="419" /></a></p>
<p>There are still a few things I might try and work out, but I am now quite satisfied with this implementation.  You can pull the Blog module out of the system and it will simply not be loaded when the application restarts. We can now also dynamically update our modules without worrying about our parent ASP.NET MVC application.  I hope you enjoy it, let me know what you think.</p>
<p><a href="http://www.fidelitydesign.net/wp-content/uploads/2010/05/RevisedMVCwithMEF.zip">Download VS2010 Project</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104&amp;headline=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104&amp;title=Modular+ASP.NET+MVC+using+the+Managed+Extensibility+Framework+%28MEF%29%2C+Part+One&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D104" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=vSlkncOu7o8:rCiey8rtLFw:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=vSlkncOu7o8:rCiey8rtLFw:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=vSlkncOu7o8:rCiey8rtLFw:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=vSlkncOu7o8:rCiey8rtLFw:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=vSlkncOu7o8:rCiey8rtLFw:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=vSlkncOu7o8:rCiey8rtLFw:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=vSlkncOu7o8:rCiey8rtLFw:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=vSlkncOu7o8:rCiey8rtLFw:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/vSlkncOu7o8" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=104</wfw:commentRss>
		<slash:comments>7</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=104</feedburner:origLink></item>
		<item>
		<title>Burned my Feed</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/Fh47F-Z6K9Y/</link>
		<comments>http://www.fidelitydesign.net/?p=103#comments</comments>
		<pubDate>Tue, 13 Apr 2010 06:44:51 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Personal]]></category>
		<category><![CDATA[blog]]></category>
		<category><![CDATA[rss]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=103</guid>
		<description><![CDATA[Moved RSS Feed Management over to FeedBurner so I can better track stats and get a general feel of how my blog content is being consumed. New feed URL: http://feeds.feedburner.com/FidelityDesign
]]></description>
			<content:encoded><![CDATA[<p>Moved RSS Feed Management over to FeedBurner so I can better track stats and get a general feel of how my blog content is being consumed. New feed URL: <a href="http://feeds.feedburner.com/FidelityDesign">http://feeds.feedburner.com/FidelityDesign</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103&amp;title=Burned+my+Feed" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103&amp;title=Burned+my+Feed" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103&amp;title=Burned+my+Feed" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103&amp;headline=Burned+my+Feed" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Burned+my+Feed&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Burned+my+Feed&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Burned+my+Feed&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Burned+my+Feed&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Burned+my+Feed&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103&amp;title=Burned+my+Feed&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D103" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Fh47F-Z6K9Y:qSHoj15_s0E:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Fh47F-Z6K9Y:qSHoj15_s0E:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Fh47F-Z6K9Y:qSHoj15_s0E:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Fh47F-Z6K9Y:qSHoj15_s0E:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Fh47F-Z6K9Y:qSHoj15_s0E:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Fh47F-Z6K9Y:qSHoj15_s0E:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=Fh47F-Z6K9Y:qSHoj15_s0E:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=Fh47F-Z6K9Y:qSHoj15_s0E:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/Fh47F-Z6K9Y" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=103</wfw:commentRss>
		<slash:comments>0</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=103</feedburner:origLink></item>
		<item>
		<title>Mocking in Javascript</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/wS-vCMLGQek/</link>
		<comments>http://www.fidelitydesign.net/?p=95#comments</comments>
		<pubDate>Thu, 08 Apr 2010 07:17:18 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[mocking]]></category>
		<category><![CDATA[moq]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=95</guid>
		<description><![CDATA[While I do most of my coding in C#, there is still a lot of work I do which resides in the client, namely the browser.  While we can employ nice unit testing and mocking frameworks in C#, the same can&#8217;t be said for Javascript.  There has been a large uptake of Javascript [...]]]></description>
			<content:encoded><![CDATA[<p>While I do most of my coding in C#, there is still a lot of work I do which resides in the client, namely the browser.  While we can employ nice unit testing and mocking frameworks in C#, the same can&#8217;t be said for Javascript.  There has been a large uptake of Javascript frameworks in these recent years, such as the quite awesome JQuery library.  With such a large move into client-side development, it becomes necessary to expand on the tools available for this development platform.</p>
<p>I&#8217;ve been introduced to Moq in C#, which I find to be easy to pick up and has a nice syntax.  Generally when mocking an interface, we can simply do:</p>
<pre class="brush: csharp">
  public interface ICalculatorService
  {
    int Add(int operandA, int operandB);
  }
</pre>
<pre class="brush: csharp">
  var mock = new Mock&lt;ICalculatorService&gt;();
  mock.Setup(c =&gt; c.Add(It.IsAny&lt;int&gt;(), It.IsAny&lt;int&gt;())).Returns(100);

  int result = mock.Object.Add(1, 2); // Will return 100.
</pre>
<p>In the above example, I&#8217;m simply telling the Moq framework that when the Add method is called on the mocked interface, with any integer for both operands, then return 100.  This simple syntax makes writing mocks relatively painless.  I wondered if this could also be done in Javascript.</p>
<p>What I set out to do, is create a simple mocking framework in Javascript which behaves similarly to Moq.</p>
<p>As Javascript has no concept of interfaces and contract based programming, we can mimick this ability using a javascript object.  If we can imagine this following as a pseudo interface:</p>
<pre class="brush: csharp">
  var ICalculatorService = {
    Add: function() {}
  };
</pre>
<p>To be able to handle the binding betwen the mocked object and it&#8217;s associated members, we can create a type called a MockBinding:</p>
<pre class="brush: csharp">
var MockBinding = function(name, member, args) {
    this.Name = name;
    this.Member = member;
    this.Arguments = args;
};
MockBinding.prototype = {
    Satisfies: function(args) {
        if (typeof(this.Arguments) == "undefined") return true;
        if (this.Arguments == null &#038;&#038; args == null) return true;
        if (this.Arguments == null || args == null) return false;
        if (this.Arguments.length != args.length) return false;

        for (var i = 0; i < this.Arguments.length; i++) {
            var argA = this.Arguments[i];
            var argB = args[i];

            var typeA = typeof(argA);
            var typeB = typeof(argB);

            if (typeA == typeB &#038;&#038; argA == argB) continue;
            if (argA == Is.AnyString &#038;&#038; typeB == "string") continue;
            if (argA == Is.AnyNumber &#038;&#038; typeB == "number") continue;
            if (argA == Is.AnyObject &#038;&#038; typeB == "object") continue;
            if (argA == Is.AnyFunction &#038;&#038; typeB == "function") continue;
            if (argA == Is.Undefined &#038;&#038; typeB == "undefined") continue;
            return false;
        }
        return true;
    }
};
</pre>
<p>With this binding, we can create properties for the name (this is the name of the member), the value of the member, and arguments (where the member is a function).  We also add in a method which allows us to compare a set of arguments to see if the current binding would satisfy those bindings.  The Satisfies method will firstly check the obvious things, undefined, nulls, array lengths.  If that all passes, we can then check the argument types. I've defined an enumeration (of sorts):</p>
<pre class="brush: csharp">
var Is = {
    AnyString: "@any-string",
    AnyNumber: "@any-number",
    AnyObject: "@any-object",
    AnyFunction: "@any-function",
    Undefined: "@undefined"
};
</pre>
<p>There is no real reason behind the values, they could be anything, numbers, etc.</p>
<p>Next, I defined a utility class for creating the actual mocked object:</p>
<pre class="brush: csharp">
var MockUtility = {};
MockUtility._emptyFunction = function() { };
MockUtility.CreateMockedObject = function(graph) {
    var object = {};
    for (var member in graph) {
        var type = typeof(graph[member]);
        if (type == "string" || type == "object") object[member] = null;
        else if (type == "number") object[member] = 0;
        else if (type == "function") object[member] = MockUtility._emptyFunction;
        else object[member] = null;
    }
    return object;
};
</pre>
<p>The cool thing about javascript objects, is that they are all essentially maps of key-value properties.  When we access a propery of an object, we can do so either through dot notation (e.g. c.Add(...)), or through index notation (e.g. c["Add"](...)).  We take advantage of this when we create our mocked object.  We enumerate over the members in the target object, and create stubs in the mocked object.  Strings and objects become null, numbers become 0, functions get set to the empty function property, etc.  The result is a copy of the object with stub members, ready to be configured.</p>
<p>Configuration is done using the mock class:</p>
<pre class="brush: csharp">
var Mock = function(graph) {
    this.Bindings = new Array();
    this.Object = MockUtility.CreateMockedObject(graph);
};
Mock.prototype = {
    Setup: function(name, member, args) {
        var object = this.Object;
        var bindings = this.Bindings;

        var binding = new MockBinding(name, member, args);
        bindings.push(binding);

        if (object[name] != undefined) {
            if (typeof(object[name]) == "function") {
                object[name] = function() {
                    for (var i = 0; i < bindings.length; i++) {
                        if (bindings[i].Name == name &#038;&#038; bindings[i].Satisfies(arguments)) {
                            return bindings[i].Member.apply(object, arguments);
                        }
                    }
                }
            } else {
                object[name] = binding.Member;
            }
        }
    }
};
</pre>
<p>When we create an instance of the Mock class, we can use the Mock utility class to create the mocked object and assign it to the Object property of the mock instance.  The prototype of the mock class defines the setup method.  When we pass a function to the setup method, we create a binding and save any arguments being passed.  The function of the object member is not the mocked function itself, but an intermediate function which matches the arguments being passed in to a saved binding.  If any other type is passed in, the value is set in the mocked object directly.</p>
<p>Using the above, we can craft a (hopefully readable) mocked example that uses the mocked framework define here:</p>
<p>We define our interface again, and create a mocked instance:</p>
<pre class="brush: csharp">
var ICalculatorService = {
    Add: function() {}
};
var mock = new Mock(ICalculatorService);
</pre>
<p>We can then configure the mock.  In our example , we'll make the result of the Add operation return 100 constantly:</p>
<pre class="brush: csharp">
mock.Setup("Add", function(operandA, operandB) {
    return 100;
}, [Is.AnyNumber, Is.AnyNumber]);
</pre>
<p>Next, we create our consumer class which uses an instance of the ICalculatorService:</p>
<pre class="brush: csharp">
var Calculator = function(service) {
    this.Service = service;
};
Calculator.prototype = {
    Add: function(operandA, operandB) {
        return this.Service.Add(operandA, operandB);
    }
};
</pre>
<p>Now, hopefully, when we call the Add operation, it should return 100 regardless, thanks to the mocked object.</p>
<pre class="brush: csharp">
var calc = new Calculator(mock.Object);
var result = calc.Add(1, 2);
// result should be 100,
</pre>
<p>So, hopefully this is a good start to developing a nice Mocking framework, probably to be utilised alongside a Javascript unit testing framework.</p>
<p>The script is attached, let me know what you think of the initial version.<br />
<a href='http://www.fidelitydesign.net/wp-content/uploads/2010/04/Mock.zip'>Mock.zip</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95&amp;title=Mocking+in+Javascript" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95&amp;title=Mocking+in+Javascript" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95&amp;title=Mocking+in+Javascript" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95&amp;headline=Mocking+in+Javascript" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Mocking+in+Javascript&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Mocking+in+Javascript&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Mocking+in+Javascript&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Mocking+in+Javascript&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Mocking+in+Javascript&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95&amp;title=Mocking+in+Javascript&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D95" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=wS-vCMLGQek:5cT7KeefQDg:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=wS-vCMLGQek:5cT7KeefQDg:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=wS-vCMLGQek:5cT7KeefQDg:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=wS-vCMLGQek:5cT7KeefQDg:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=wS-vCMLGQek:5cT7KeefQDg:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=wS-vCMLGQek:5cT7KeefQDg:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=wS-vCMLGQek:5cT7KeefQDg:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=wS-vCMLGQek:5cT7KeefQDg:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/wS-vCMLGQek" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=95</wfw:commentRss>
		<slash:comments>1</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=95</feedburner:origLink></item>
		<item>
		<title>Using MEF with MVC Controllers</title>
		<link>http://feedproxy.google.com/~r/FidelityDesign/~3/czy7rjK5acA/</link>
		<comments>http://www.fidelitydesign.net/?p=88#comments</comments>
		<pubDate>Tue, 16 Mar 2010 14:54:57 +0000</pubDate>
		<dc:creator>Matthew Abbott</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Controller]]></category>
		<category><![CDATA[MEF]]></category>
		<category><![CDATA[mvc]]></category>

		<guid isPermaLink="false">http://www.fidelitydesign.net/?p=88</guid>
		<description><![CDATA[I&#8217;ve recently been introduced to the Managed Extensibility Framework by a colleague at work, and have enjoyed picking it up so much it made me wonder how I could apply the simplicity of composition into my favourite web framework, ASP.NET MVC.  There are a few obstacles to overcome initially, namely how instances are composed [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve recently been introduced to the Managed Extensibility Framework by a colleague at work, and have enjoyed picking it up so much it made me wonder how I could apply the simplicity of composition into my favourite web framework, ASP.NET MVC.  There are a few obstacles to overcome initially, namely how instances are composed by default, and how the MVC system handles custom controllers.  The idea behind this project, is to enable a Controller to be developed and deployed in it&#8217;s own assembly, with the ability to drop it into a project as an extension.  Thus, as is the nature of MEF, this was down to exports and imports.  MVC allows us to customise how controllers are created by implementing our own controller factory, so we can use this as well.</p>
<p>This initial problem with how MEF would work with MVC controllers, is that a controller is created when it is needed, not composed (and instantiated) straight away.  In MEF preview 9, a great example project exists called DynamicInstantiation.  In said project they&#8217;ve created a custom export provider and types, the PartCreator types.  Using this method they can get the benefits of automatic composure with the added extra of dynamic instantiation.  Basically, they can create instances of their dynamicly imported types, as and when they chose.  This seemed pretty perfect for what I wanted to do with MVC.</p>
<p>I&#8217;ve taken that example project, fleshed out the code with comments and renamed the PartCreator types as PartFactory (that&#8217;s just my personal preference).</p>
<p>To get started with the project itself, I looked at the requirement for a controller.  I&#8217;ve created a class library solely to house the custom controllers TestController. I&#8217;ve used [Export(typeof(IController))] to mark my controller for export, and also [ExportMetadata("ControllerName", "Test")] to mark my export with my desired metadata.  This metadata will come into play later when we are instantiating an instance of our controller. I don&#8217;t need to define my own controller contract, as we can use the IController interface as our export definition.</p>
<pre class="brush: csharp">namespace MEFLearning.MVC
{
    using System.ComponentModel.Composition;
    using System.Web.Mvc;

    /// &lt;summary&gt;
    /// Defines an importable controller.
    /// &lt;/summary&gt;
    [Export(typeof(IController)), ExportMetadata("ControllerName", "Test")]
    public class TestController : Controller
    {
        #region Actions
        /// &lt;summary&gt;
        /// The default action for the controller.
        /// &lt;/summary&gt;
        /// &lt;remarks&gt;
        /// As this is just an example, we'll redirect the user back to the homepage.
        /// &lt;/remarks&gt;
        public ActionResult Index()
        {
            return RedirectToAction("Index", "Home");
        }
        #endregion
    }
}</pre>
<p>Using the DynamicInstantiationExportProvider, we can create imports of PartFactory&lt;IController, IControllerMetadata&gt;, instead of imports of IController.  This is important, as when we compose whatever type is required, we don&#8217;t want it to automatically create instances of our controller.  This only need happen when a request is made.  To this end, I&#8217;ve created a new IControllerFactory, which allows us to create an instance of the controller only when it is required:</p>
<pre class="brush: csharp">namespace MEFLearning.Web
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel.Composition;
    using System.Linq;
    using System.Web.Mvc;

    using MEFLearning.Web.ComponentModel;

    /// &lt;summary&gt;
    /// Defines a controller factory that supports importing of controllers.
    /// &lt;/summary&gt;
    [Export]
    public class ImportControllerFactory : DefaultControllerFactory
    {
        #region Properties
        /// &lt;summary&gt;
        /// Gets or sets the collection of controller part factories.
        /// &lt;/summary&gt;
        [ImportMany]
        public IEnumerable&lt;PartFactory&lt;IController, IControllerMetadata&gt;&gt; PartFactories { get; set; }
        #endregion

        #region Methods
        /// &lt;summary&gt;
        /// Creates an instance a controller with the specified controller name.
        /// &lt;/summary&gt;
        /// &lt;param name="requestContext"&gt;The context of the request.&lt;/param&gt;
        /// &lt;param name="controllerName"&gt;The name of the contorller requested.&lt;/param&gt;
        /// &lt;returns&gt;An instance a controller with the specified controller name.&lt;/returns&gt;
        public override IController CreateController(System.Web.Routing.RequestContext requestContext, string controllerName)
        {
            IController controller = null;

            if (PartFactories != null) {
                // Determine if a factory is available for our controller.
                var factory = PartFactories
                    .Where(f =&gt; (f.Metadata != null
                                 &#038;&#038; string.Equals(f.Metadata.ControllerName, controllerName,
                                                  StringComparison.InvariantCultureIgnoreCase)))
                    .FirstOrDefault();

                // Create an instance of the controller.
                if (factory != null)
                    controller = factory.CreatePart();
            }

            // If no imported controller could be found, use the default factory to create one where available.
            return controller ?? base.CreateController(requestContext, controllerName);
        }
        #endregion
    }
}</pre>
<p>When the CreateController method is called by the MVC ControllerBuilder, we need to interrogate our PartFactories enumerable to find the available imported controller.  One of the nice touches with how the imports are handled, is that the metadata we decorated on our TestController ([ExportMetadata("ControllerName", "Test")]) is projected as an instance of our interface, IControllerMetadata:</p>
<pre class="brush: csharp">namespace MEFLearning.Web
{
    /// &lt;summary&gt;
    /// Defines the interface for a controller metdata view.
    /// &lt;/summary&gt;
    public interface IControllerMetadata
    {
        #region Properties
        /// &lt;summary&gt;
        /// Gets the controller name.
        /// &lt;/summary&gt;
        string ControllerName { get; }
        #endregion
    }
}</pre>
<p>In vanilla-MVC, the controller is selected based on it&#8217;s name, minus the &#8220;Controller&#8221; suffix.  Unfortunately, this wouldn&#8217;t work well with this solution, as the imported part type is IController, not TestController, and we can&#8217;t do a GetType() call on the instance, as we would have to create an instance ahead of time to do that.  This is the design decision around using a metadata view.  If the exported controller doesn&#8217;t have a ControllerName metadata attribute, it won&#8217;t successfully be instantiated.  Small sacrifice, but I think it&#8217;s worth it.</p>
<p>I&#8217;ve used the DefaultControllerFactory type as a base, as it will allow us to create instances of controllers hosted in the main web project.  For instance, we can keep the default HomeController and AccountController types in the website itself, the above implementation will still allow us to use them.</p>
<p><strong>Routing</strong><br />
Controllers are pretty much useless without routes, and in light of the fact that MVC2 has the concept of AreaRegistration, I thought it would be a nice idea to have our routing handled by the MEF composition also.  To this end, I&#8217;ve created a new contract, the IRouteRegistrar, which has two methods, RegisterIgnoreRoutes() and RegisterRoutes().  Handling these seperately allows multiple registrars to register their routes in a seperate fashion, this may be important due to the linear nature in which routes are selected.  My contract is as follows:</p>
<pre class="brush: csharp">namespace MEFLearning.MVC
{
    using System.Web.Routing;

    /// &lt;summary&gt;
    /// Defines the required contract for implemting a route registrar.
    /// &lt;/summary&gt;
    public interface IRouteRegistrar
    {
        #region Methods
        /// &lt;summary&gt;
        /// Registers any routes to be ignored.
        /// &lt;/summary&gt;
        /// &lt;param name="routes"&gt;The collection of routes to add to.&lt;/param&gt;
        void RegisterIgnoreRoutes(RouteCollection routes);

        /// &lt;summary&gt;
        /// Registers any routes to be processed.
        /// &lt;/summary&gt;
        /// &lt;param name="routes"&gt;The collection of routes to add to.&lt;/param&gt;
        void RegisterRoutes(RouteCollection routes);
        #endregion
    }
}</pre>
<p>We can take advantage of this, by having our default rules be implemented as a registrar:</p>
<pre class="brush: csharp">namespace MEFLearning.Web
{
    using System.ComponentModel.Composition;
    using System.Web.Mvc;
    using System.Web.Routing;

    using MEFLearning.MVC;

    /// &lt;summary&gt;
    /// Registers the default required routes.
    /// &lt;/summary&gt;
    [Export(typeof(IRouteRegistrar))]
    public class DefaultRouteRegistrar : IRouteRegistrar
    {
        #region Methods
        /// &lt;summary&gt;
        /// Registers any routes to be ignored.
        /// &lt;/summary&gt;
        /// &lt;param name="routes"&gt;The collection of routes to add to.&lt;/param&gt;
        public void RegisterIgnoreRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
            routes.IgnoreRoute("{resource}.ico/{*pathInfo}");
        }

        /// &lt;summary&gt;
        /// Registers any routes to be processed.
        /// &lt;/summary&gt;
        /// &lt;param name="routes"&gt;The collection of routes to add to.&lt;/param&gt;
        public void RegisterRoutes(RouteCollection routes)
        {
            routes.MapRoute("Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" });
        }
        #endregion
    }
}</pre>
<p>The DefaultRouteRegistrar is in the main website project, but having the ability to export our local types means it now fits nicely into our composition. For this example, I haven&#8217;t bothered creating any routes for the TestController, as the default route will handle it for now.  I have created a TestRouteRegistrar stub which can be fleshed out when more complex routes are required.</p>
<p><strong>Joing it all together</strong><br />
Originally I toyed with having a seperate host class that we could reference from our Global application class.  In the end though, it&#8217;s perfectly viable to just use the MvcApplication type thats generated with our project as our composable type. Firstly, lets look at how we are composing our application:</p>
<pre class="brush: csharp">#region Properties
/// &lt;summary&gt;
/// Gets or sets the collection of route registrars.
/// &lt;/summary&gt;
[ImportMany]
public IEnumerable&lt;IRouteRegistrar&gt; RouteRegistrars { get; set; }

/// &lt;summary&gt;
/// Gets or sets the controller factory used for imported controllers.
/// &lt;/summary&gt;
[Import]
public ImportControllerFactory ControllerFactory { get; private set; }
#endregion</pre>
<p>We decorate two properties here.  We need our route registrars composed and available straight away, as with our custom controller factory.  This all fits togther with our Application_Start method:</p>
<pre class="brush: csharp">protected void Application_Start()
{
    // Create our part catalog and export provider.
    var catalog = new AggregateCatalog(
        new DirectoryCatalog(Server.MapPath("~/bin")),
        new DirectoryCatalog(Server.MapPath("~/bin/Imports")));
    var exportProvider = new DynamicInstantiationExportProvider();

    // Create the container used to compose parts.
    var container = new CompositionContainer(catalog, exportProvider);
    exportProvider.SourceProvider = container;

    // Compose our application.
    container.ComposeParts(this);

    // Set the controller builder to use our custom controller factory.
    ControllerBuilder.Current.SetControllerFactory(ControllerFactory);

    // Register any available routes.
    RegisterRoutes();
}</pre>
<p>The nuts and bolts of it are a single AggregateCatalog which itself is composed of two DirectCatalog instances, one for the main application types (&#8220;~/bin&#8221;), and our for our imported types (&#8220;~/bin/Imports&#8221;).  Not sure if it&#8217;s just me, but I was hoping the DirectoryCatalog would handle subdirectories (have I missed that)?  </p>
<p>We create an instance of our DynamicInstantiationExportProvider which will allow the composition of PartFactory&lt;&gt; instances.  Once thats all be composed, we can assign our ImportControllerFactory to the ControllerBuilder and register our routes:</p>
<pre class="brush: csharp">/// &lt;summary&gt;
/// Registers any required routes.
/// &lt;/summary&gt;
public void RegisterRoutes()
{
    RouteCollection routes = RouteTable.Routes;

    // Register our ignore routes.
    foreach (var registrar in RouteRegistrars)
        registrar.RegisterIgnoreRoutes(routes);

    // Register our processed routes.
    foreach (var registrar in RouteRegistrars)
        registrar.RegisterRoutes(routes);
}</pre>
<p>Thats pretty much it, run the project and visit the /Test url, if all goes to plan it should redirect you back to the homepage.  We could have done something a bit fancier, but I think this is a good starting point to a modular MVC project.  </p>
<p>The project is attached for your viewing, let me know what you think.</p>
<p><a href="http://www.fidelitydesign.net/uploads/MEF-MVCControllers.rar">MEF-MVCControllers.rar</a></p>
<div class="lightsocial_container"><a class="lightsocial_a" href="http://digg.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88&amp;title=Using+MEF+with+MVC+Controllers" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/digg.png" alt="Digg This" title="Digg This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.reddit.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88&amp;title=Using+MEF+with+MVC+Controllers" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/reddit.png" alt="Reddit This" title="Reddit This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.stumbleupon.com/submit?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88&amp;title=Using+MEF+with+MVC+Controllers" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/stumbleupon.png" alt="Stumble Now!" title="Stumble Now!" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://buzz.yahoo.com/buzz?targetUrl=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88&amp;headline=Using+MEF+with+MVC+Controllers" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/yahoo_buzz.png" alt="Buzz This" title="Buzz This" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dzone.com/links/add.html?title=Using+MEF+with+MVC+Controllers&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dzone.png" alt="Vote on DZone" title="Vote on DZone" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.facebook.com/sharer.php?t=Using+MEF+with+MVC+Controllers&amp;u=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/facebook.png" alt="Share on Facebook" title="Share on Facebook" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://delicious.com/save?title=Using+MEF+with+MVC+Controllers&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/delicious.png" alt="Bookmark this on Delicious" title="Bookmark this on Delicious" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.dotnetkicks.com/kick/?title=Using+MEF+with+MVC+Controllers&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetkicks.png" alt="Kick It on DotNetKicks.com" title="Kick It on DotNetKicks.com" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://dotnetshoutout.com/Submit?title=Using+MEF+with+MVC+Controllers&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/dotnetshoutout.png" alt="Shout it" title="Shout it" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.linkedin.com/shareArticle?mini=true&amp;url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88&amp;title=Using+MEF+with+MVC+Controllers&amp;summary=&amp;source=" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/linkedin.png" alt="Share on LinkedIn" title="Share on LinkedIn" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.technorati.com/faves?add=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/technorati.png" alt="Bookmark this on Technorati" title="Bookmark this on Technorati" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://twitter.com/home?status=Reading+http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/twitter.png" alt="Post on Twitter" title="Post on Twitter" /></a>&nbsp;&nbsp;<a class="lightsocial_a" href="http://www.google.com/buzz/post?url=http%3A%2F%2Fwww.fidelitydesign.net%2F%3Fp%3D88" ><img class="lightsocial_img" src="http://www.fidelitydesign.net/wp-content/plugins/light-social/google_buzz.png" alt="Google Buzz (aka. Google Reader)" title="Google Buzz (aka. Google Reader)" /></a>&nbsp;&nbsp;</div><div class="feedflare">
<a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=czy7rjK5acA:Xx_GnycIjew:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=yIl2AUoC8zA" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=czy7rjK5acA:Xx_GnycIjew:F7zBnMyn0Lo"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=czy7rjK5acA:Xx_GnycIjew:F7zBnMyn0Lo" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=czy7rjK5acA:Xx_GnycIjew:V_sGLiPBpWU"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=czy7rjK5acA:Xx_GnycIjew:V_sGLiPBpWU" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=czy7rjK5acA:Xx_GnycIjew:qj6IDK7rITs"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?d=qj6IDK7rITs" border="0"></img></a> <a href="http://feeds.feedburner.com/~ff/FidelityDesign?a=czy7rjK5acA:Xx_GnycIjew:gIN9vFwOqvQ"><img src="http://feeds.feedburner.com/~ff/FidelityDesign?i=czy7rjK5acA:Xx_GnycIjew:gIN9vFwOqvQ" border="0"></img></a>
</div><img src="http://feeds.feedburner.com/~r/FidelityDesign/~4/czy7rjK5acA" height="1" width="1"/>]]></content:encoded>
			<wfw:commentRss>http://www.fidelitydesign.net/?feed=rss2&amp;p=88</wfw:commentRss>
		<slash:comments>15</slash:comments>
		<feedburner:origLink>http://www.fidelitydesign.net/?p=88</feedburner:origLink></item>
	</channel>
</rss>
