<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" version="2.0">
  <channel>
    <title>ploeh blog</title>
    <link>http://blog.ploeh.dk/</link>
    <description>Mark Seemann's .NET blog</description>
    <language>en-us</language>
    <copyright>Mark Seemann</copyright>
    <lastBuildDate>Mon, 08 Feb 2010 19:15:41 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>mark@seemann.ms</managingEditor>
    <webMaster>mark@seemann.ms</webMaster>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=d81e68f1-5cd0-4a96-9881-5b7bc250c641</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,d81e68f1-5cd0-4a96-9881-5b7bc250c641.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,d81e68f1-5cd0-4a96-9881-5b7bc250c641.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=d81e68f1-5cd0-4a96-9881-5b7bc250c641</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
As part of the Copenhagen .NET User Group (CNUG) winter and early autumn schedule,
I’ll be giving a talk on (slightly advanced) TDD.
</p>
        <p>
The talk will be in Danish and takes place April 15th, 2010. More details and sign-up <a href="http://www.eventbrite.com/event/567027996/">here</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d81e68f1-5cd0-4a96-9881-5b7bc250c641" />
      </body>
      <title>CNUG TDD talk</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,d81e68f1-5cd0-4a96-9881-5b7bc250c641.aspx</guid>
      <link>http://blog.ploeh.dk/2010/02/08/CNUGTDDTalk.aspx</link>
      <pubDate>Mon, 08 Feb 2010 19:15:41 GMT</pubDate>
      <description>&lt;p&gt;
As part of the Copenhagen .NET User Group (CNUG) winter and early autumn schedule,
I’ll be giving a talk on (slightly advanced) TDD.
&lt;/p&gt;
&lt;p&gt;
The talk will be in Danish and takes place April 15th, 2010. More details and sign-up &lt;a href="http://www.eventbrite.com/event/567027996/"&gt;here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d81e68f1-5cd0-4a96-9881-5b7bc250c641" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,d81e68f1-5cd0-4a96-9881-5b7bc250c641.aspx</comments>
      <category>Miscellaneous</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=89bf0c61-5cf2-4e92-8b53-fa0a10d06945</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=89bf0c61-5cf2-4e92-8b53-fa0a10d06945</wfw:commentRss>
      <slash:comments>14</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Service Locator is a well-known pattern, and since it was <a href="http://martinfowler.com/articles/injection.html">described
by Martin Fowler</a>, it must be good, right?
</p>
        <p>
No, it’s actually an <strong>anti-pattern</strong> and should be avoided.
</p>
        <p>
Let’s examine why this is so. In short, the problem with Service Locator is that it
hides a class’ dependencies, causing run-time errors instead of compile-time errors,
as well as making the code more difficult to maintain because it becomes unclear when
you would be introducing a breaking change.
</p>
        <p>
          <strong>OrderProcessor example</strong>
        </p>
        <p>
As an example, let’s pick a hot topic in DI these days: an OrderProcessor. To process
an order, the OrderProcessor must validate the order and ship it if valid. Here’s
an example using a static Service Locator:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">OrderProcessor</span> : <span style="color: #2b91af">IOrderProcessor</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> validator
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> shipper
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">            shipper.Ship(order);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The Service Locator is used as a replacement for the <em>new</em> operator. It looks
like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&lt;T&gt;(\cf2 Func\cf0 &lt;T&gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&gt; resolver();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  T Resolve&lt;T&gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">static</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Locator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">static</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;</pre>
          <pre style="margin: 0px">        services = <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Register&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;T&gt;
resolver)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]
= () =&gt; resolver();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span> T
Resolve&lt;T&gt;()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> (T)<span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Reset()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services.Clear();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
We can configure the Locator using the Register method. A ‘real’ Service Locator implementation
would be much more advanced than this, but this example captures the gist of it.
</p>
        <p>
This is flexible and extensible, and it even supports replacing services with Test
Doubles, as we will see shortly.
</p>
        <p>
Given that, then what could be the problem?
</p>
        <p>
          <strong>API usage issues</strong>
        </p>
        <p>
Let’s assume for a moment that we are simply consumers of the OrderProcessor class.
We didn’t write it ourselves, it was given to us in an assembly by a third party,
and we have yet to look at it in Reflector.
</p>
        <p>
This is what we get from IntelliSense in Visual Studio:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_3.png" width="317" height="52" />
        </p>
        <p>
Okay, so the class has a default constructor. That means I can simply create a new
instance of it and invoke the Process method right away:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 ();\par sut.Process(order);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= <span style="color: blue">new</span><span style="color: #2b91af">Order</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">OrderProcessor</span>();</pre>
          <pre style="margin: 0px">sut.Process(order);</pre>
        </div>
        <p>
Alas, running this code surprisingly throws a KeyNotFoundException because the IOrderValidator
was never registered with Locator. This is not only surprising, it may be quite baffling
if we don’t have access to the source code.
</p>
        <p>
By perusing the source code (or using Reflector) or consulting the documentation (ick!)
we may finally discover that we need to register an IOrderValidator instance with
Locator (a completely unrelated static class) before this will work.
</p>
        <p>
In a unit test test, this can be done like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  validatorStub = \cf1 new\cf0  \cf2 Mock\cf0 &lt;\cf2 IOrderValidator\cf0 &gt;();\par validatorStub.Setup(v =&gt; v.Validate(order)).Returns(\cf1 false\cf0 );\par \cf2 Locator\cf0 .Register(() =&gt; validatorStub.Object);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> validatorStub
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">validatorStub.Setup(v =&gt; v.Validate(order)).Returns(<span style="color: blue">false</span>);</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">Locator</span>.Register(()
=&gt; validatorStub.Object);</pre>
        </div>
        <p>
What is even more annoying is that because the Locator’s internal store is static,
we need to invoke the Reset method after each unit test, but granted: that is mainly
a unit testing issue.
</p>
        <p>
All in all, however, we can’t reasonably claim that this sort of API provides a positive
developer experience.
</p>
        <p>
          <strong>Maintenance issues</strong>
        </p>
        <p>
While this use of Service Locator is problematic from the consumer’s point of view,
what seems easy soon becomes an issue for the maintenance developer as well.
</p>
        <p>
Let’s say that we need to expand the behavior of OrderProcessor to also invoke the <a href="http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx">IOrderCollector.Collect
method</a>. This is easily done, or is it?
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  collector = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderCollector\cf0 &gt;();\par         collector.Collect(order);\par         \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> validator
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> collector
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderCollector</span>&gt;();</pre>
          <pre style="margin: 0px">        collector.Collect(order);</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> shipper
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">        shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
From a pure mechanistic point of view, that was easy – we simply added a new call
to Locator.Resolve and invoke IOrderCollector.Collect.
</p>
        <p>
Was this a breaking change?
</p>
        <p>
This can be surprisingly hard to answer. It certainly compiled fine, but broke one
of my unit tests. What happens in a production application? The IOrderCollector interface
may already be registered with the Service Locator because it is already in use by
other components, in which case it will work without a hitch. On the other hand, this
may not be the case.
</p>
        <p>
The bottom line is that it becomes a lot harder to tell whether you are introducing
a breaking change or not. You need to understand the <em>entire</em> application in
which the Service Locator is being used, and the compiler is not going to help you.
</p>
        <p>
          <strong>Variation: Concrete Service Locator</strong>
        </p>
        <p>
Can we fix these issues in some way?
</p>
        <p>
One variation commonly encountered is to make the Service Locator a concrete class,
used like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par     \cf1 var\cf0  validator = locator.Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  shipper = locator.Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> locator
= <span style="color: blue">new</span><span style="color: #2b91af">Locator</span>();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> validator
= locator.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> shipper
= locator.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">        shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
However, to be configured, it still needs a static in-memory store:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&lt;T&gt;(\cf2 Func\cf0 &lt;T&gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&lt;T&gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Locator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">static</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;</pre>
          <pre style="margin: 0px">        services = <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Register&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;T&gt;
resolver)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]
= () =&gt; resolver();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> T
Resolve&lt;T&gt;()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> (T)<span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Reset()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services.Clear();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In other words: there’s no structural difference between the concrete Service Locator
and the static Service Locator we already reviewed. It has the same issues and solves
nothing.
</p>
        <p>
          <strong>Variation: Abstract Service Locator</strong>
        </p>
        <p>
A different variation seems more in line with true DI: the Service Locator is a concrete
class implementing an interface.
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 interface\cf0  \cf2 IServiceLocator\cf0 \par \{\par     T Resolve&lt;T&gt;();\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IServiceLocator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    T Resolve&lt;T&gt;();</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
        </div>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0  : \cf2 IServiceLocator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt; services;\par \par     \cf1 public\cf0  Locator()\par     \{\par         \cf1 this\cf0 .services = \cf1 new\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;();\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Register&lt;T&gt;(\cf2 Func\cf0 &lt;T&gt; resolver)\par     \{\par         \cf1 this\cf0 .services[\cf1 typeof\cf0 (T)] = () =&gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&lt;T&gt;()\par     \{\par         \cf1 return\cf0  (T)\cf1 this\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Locator</span> : <span style="color: #2b91af">IServiceLocator</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;
services;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> Locator()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.services
= <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Register&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;T&gt;
resolver)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.services[<span style="color: blue">typeof</span>(T)]
= () =&gt; resolver();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> T
Resolve&lt;T&gt;()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> (T)<span style="color: blue">this</span>.services[<span style="color: blue">typeof</span>(T)]();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
With this variation it becomes necessary to inject the Service Locator into the consumer. <strong>Constructor
Injection</strong> is always a good choice for injecting dependencies, so OrderProcessor
morphs into this implementation:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IServiceLocator\cf0  locator;\par \par     \cf1 public\cf0  OrderProcessor(\cf2 IServiceLocator\cf0  locator)\par     \{\par         \cf1 if\cf0  (locator == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "locator"\cf0 );\par         \}\par \par         \cf1 this\cf0 .locator = locator;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \par             \cf1 this\cf0 .locator.Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper =\par                 \cf1 this\cf0 .locator.Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">OrderProcessor</span> : <span style="color: #2b91af">IOrderProcessor</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IServiceLocator</span> locator;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> OrderProcessor(<span style="color: #2b91af">IServiceLocator</span> locator)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (locator
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"locator"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.locator
= locator;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> validator
= </pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.locator.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> shipper
=</pre>
          <pre style="margin: 0px">                <span style="color: blue">this</span>.locator.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">            shipper.Ship(order);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Is this good, then?
</p>
        <p>
From a developer perspective, we now get a bit of help from IntelliSense:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_6.png" width="474" height="47" />
        </p>
        <p>
What does this tell us? Nothing much, really. Okay, so OrderProcessor needs a ServiceLocator
– that’s a bit more information than before, but it still doesn’t tell us <em>which
services</em> are needed. The following code compiles, but crashes with the same KeyNotFoundException
as before:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 (locator);\par sut.Process(order);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= <span style="color: blue">new</span><span style="color: #2b91af">Order</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> locator
= <span style="color: blue">new</span><span style="color: #2b91af">Locator</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">OrderProcessor</span>(locator);</pre>
          <pre style="margin: 0px">sut.Process(order);</pre>
        </div>
        <p>
From the maintenance developer’s point of view, things don’t improve much either.
We still get no help if we need to add a new dependency: is it a breaking change or
not? Just as hard to tell as before.
</p>
        <p>
          <strong>Summary</strong>
        </p>
        <p>
The problem with using a Service Locator isn’t that you take a dependency on a particular
Service Locator implementation (although that may be a problem as well), but that
it’s a bona-fide <strong>anti-pattern</strong>. It will give consumers of your API
a horrible developer experience, and it will make your life as a maintenance developer
worse because you will need to use considerable amounts of brain power to grasp the
implications of every change you make.
</p>
        <p>
The compiler can offer both consumers and producers so much help when <strong>Constructor
Injection</strong> is used, but none of that assistance is available for APIs that
rely on Service Locator.
</p>
        <p>
You can read more about DI patterns and anti-patterns in <a href="http://www.manning.com/seemann/">my
upcoming book</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=89bf0c61-5cf2-4e92-8b53-fa0a10d06945" />
      </body>
      <title>Service Locator is an Anti-Pattern</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</guid>
      <link>http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx</link>
      <pubDate>Wed, 03 Feb 2010 21:49:39 GMT</pubDate>
      <description>&lt;p&gt;
Service Locator is a well-known pattern, and since it was &lt;a href="http://martinfowler.com/articles/injection.html"&gt;described
by Martin Fowler&lt;/a&gt;, it must be good, right?
&lt;/p&gt;
&lt;p&gt;
No, it’s actually an &lt;strong&gt;anti-pattern&lt;/strong&gt; and should be avoided.
&lt;/p&gt;
&lt;p&gt;
Let’s examine why this is so. In short, the problem with Service Locator is that it
hides a class’ dependencies, causing run-time errors instead of compile-time errors,
as well as making the code more difficult to maintain because it becomes unclear when
you would be introducing a breaking change.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;OrderProcessor example&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
As an example, let’s pick a hot topic in DI these days: an OrderProcessor. To process
an order, the OrderProcessor must validate the order and ship it if valid. Here’s
an example using a static Service Locator:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderProcessor&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The Service Locator is used as a replacement for the &lt;em&gt;new&lt;/em&gt; operator. It looks
like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&amp;lt;T&amp;gt;(\cf2 Func\cf0 &amp;lt;T&amp;gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&amp;gt; resolver();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  T Resolve&amp;lt;T&amp;gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; services = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Register&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
resolver)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]
= () =&amp;gt; resolver();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; T
Resolve&amp;lt;T&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; (T)&lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Reset()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services.Clear();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We can configure the Locator using the Register method. A ‘real’ Service Locator implementation
would be much more advanced than this, but this example captures the gist of it.
&lt;/p&gt;
&lt;p&gt;
This is flexible and extensible, and it even supports replacing services with Test
Doubles, as we will see shortly.
&lt;/p&gt;
&lt;p&gt;
Given that, then what could be the problem?
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;API usage issues&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Let’s assume for a moment that we are simply consumers of the OrderProcessor class.
We didn’t write it ourselves, it was given to us in an assembly by a third party,
and we have yet to look at it in Reflector.
&lt;/p&gt;
&lt;p&gt;
This is what we get from IntelliSense in Visual Studio:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_3.png" width="317" height="52"&gt; 
&lt;/p&gt;
&lt;p&gt;
Okay, so the class has a default constructor. That means I can simply create a new
instance of it and invoke the Process method right away:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 ();\par sut.Process(order);\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.Process(order);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Alas, running this code surprisingly throws a KeyNotFoundException because the IOrderValidator
was never registered with Locator. This is not only surprising, it may be quite baffling
if we don’t have access to the source code.
&lt;/p&gt;
&lt;p&gt;
By perusing the source code (or using Reflector) or consulting the documentation (ick!)
we may finally discover that we need to register an IOrderValidator instance with
Locator (a completely unrelated static class) before this will work.
&lt;/p&gt;
&lt;p&gt;
In a unit test test, this can be done like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  validatorStub = \cf1 new\cf0  \cf2 Mock\cf0 &amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par validatorStub.Setup(v =&amp;gt; v.Validate(order)).Returns(\cf1 false\cf0 );\par \cf2 Locator\cf0 .Register(() =&amp;gt; validatorStub.Object);\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; validatorStub
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;validatorStub.Setup(v =&amp;gt; v.Validate(order)).Returns(&lt;span style="color: blue"&gt;false&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Register(()
=&amp;gt; validatorStub.Object);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What is even more annoying is that because the Locator’s internal store is static,
we need to invoke the Reset method after each unit test, but granted: that is mainly
a unit testing issue.
&lt;/p&gt;
&lt;p&gt;
All in all, however, we can’t reasonably claim that this sort of API provides a positive
developer experience.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Maintenance issues&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
While this use of Service Locator is problematic from the consumer’s point of view,
what seems easy soon becomes an issue for the maintenance developer as well.
&lt;/p&gt;
&lt;p&gt;
Let’s say that we need to expand the behavior of OrderProcessor to also invoke the &lt;a href="http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx"&gt;IOrderCollector.Collect
method&lt;/a&gt;. This is easily done, or is it?
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  collector = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderCollector\cf0 &amp;gt;();\par         collector.Collect(order);\par         \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; collector
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; collector.Collect(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
From a pure mechanistic point of view, that was easy – we simply added a new call
to Locator.Resolve and invoke IOrderCollector.Collect.
&lt;/p&gt;
&lt;p&gt;
Was this a breaking change?
&lt;/p&gt;
&lt;p&gt;
This can be surprisingly hard to answer. It certainly compiled fine, but broke one
of my unit tests. What happens in a production application? The IOrderCollector interface
may already be registered with the Service Locator because it is already in use by
other components, in which case it will work without a hitch. On the other hand, this
may not be the case.
&lt;/p&gt;
&lt;p&gt;
The bottom line is that it becomes a lot harder to tell whether you are introducing
a breaking change or not. You need to understand the &lt;em&gt;entire&lt;/em&gt; application in
which the Service Locator is being used, and the compiler is not going to help you.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Variation: Concrete Service Locator&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Can we fix these issues in some way?
&lt;/p&gt;
&lt;p&gt;
One variation commonly encountered is to make the Service Locator a concrete class,
used like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par     \cf1 var\cf0  validator = locator.Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  shipper = locator.Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; locator
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
However, to be configured, it still needs a static in-memory store:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&amp;lt;T&amp;gt;(\cf2 Func\cf0 &amp;lt;T&amp;gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&amp;gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&amp;lt;T&amp;gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; services = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Register&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
resolver)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]
= () =&amp;gt; resolver();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; T
Resolve&amp;lt;T&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; (T)&lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Reset()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services.Clear();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In other words: there’s no structural difference between the concrete Service Locator
and the static Service Locator we already reviewed. It has the same issues and solves
nothing.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Variation: Abstract Service Locator&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
A different variation seems more in line with true DI: the Service Locator is a concrete
class implementing an interface.
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 interface\cf0  \cf2 IServiceLocator\cf0 \par \{\par     T Resolve&amp;lt;T&amp;gt;();\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;interface&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; T Resolve&amp;lt;T&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;/div&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0  : \cf2 IServiceLocator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt; services;\par \par     \cf1 public\cf0  Locator()\par     \{\par         \cf1 this\cf0 .services = \cf1 new\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;();\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Register&amp;lt;T&amp;gt;(\cf2 Func\cf0 &amp;lt;T&amp;gt; resolver)\par     \{\par         \cf1 this\cf0 .services[\cf1 typeof\cf0 (T)] = () =&amp;gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&amp;lt;T&amp;gt;()\par     \{\par         \cf1 return\cf0  (T)\cf1 this\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;
services;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; Locator()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.services
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Register&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
resolver)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]
= () =&amp;gt; resolver();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; T
Resolve&amp;lt;T&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; (T)&lt;span style="color: blue"&gt;this&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With this variation it becomes necessary to inject the Service Locator into the consumer. &lt;strong&gt;Constructor
Injection&lt;/strong&gt; is always a good choice for injecting dependencies, so OrderProcessor
morphs into this implementation:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IServiceLocator\cf0  locator;\par \par     \cf1 public\cf0  OrderProcessor(\cf2 IServiceLocator\cf0  locator)\par     \{\par         \cf1 if\cf0  (locator == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "locator"\cf0 );\par         \}\par \par         \cf1 this\cf0 .locator = locator;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \par             \cf1 this\cf0 .locator.Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper =\par                 \cf1 this\cf0 .locator.Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderProcessor&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt; locator;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; OrderProcessor(&lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt; locator)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (locator
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"locator"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.locator
= locator;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Is this good, then?
&lt;/p&gt;
&lt;p&gt;
From a developer perspective, we now get a bit of help from IntelliSense:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_6.png" width="474" height="47"&gt; 
&lt;/p&gt;
&lt;p&gt;
What does this tell us? Nothing much, really. Okay, so OrderProcessor needs a ServiceLocator
– that’s a bit more information than before, but it still doesn’t tell us &lt;em&gt;which
services&lt;/em&gt; are needed. The following code compiles, but crashes with the same KeyNotFoundException
as before:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 (locator);\par sut.Process(order);\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; locator
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt;(locator);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.Process(order);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
From the maintenance developer’s point of view, things don’t improve much either.
We still get no help if we need to add a new dependency: is it a breaking change or
not? Just as hard to tell as before.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Summary&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
The problem with using a Service Locator isn’t that you take a dependency on a particular
Service Locator implementation (although that may be a problem as well), but that
it’s a bona-fide &lt;strong&gt;anti-pattern&lt;/strong&gt;. It will give consumers of your API
a horrible developer experience, and it will make your life as a maintenance developer
worse because you will need to use considerable amounts of brain power to grasp the
implications of every change you make.
&lt;/p&gt;
&lt;p&gt;
The compiler can offer both consumers and producers so much help when &lt;strong&gt;Constructor
Injection&lt;/strong&gt; is used, but none of that assistance is available for APIs that
rely on Service Locator.
&lt;/p&gt;
&lt;p&gt;
You can read more about DI patterns and anti-patterns in &lt;a href="http://www.manning.com/seemann/"&gt;my
upcoming book&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=89bf0c61-5cf2-4e92-8b53-fa0a10d06945" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a <a href="http://jeffreypalermo.com/blog/constructor-over-injection-smell-ndash-follow-up/">follow-up</a> to
his <a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/">earlier
post on Constructor Over-Injection</a>, <a href="http://jeffreypalermo.com/">Jeffrey
Palermo</a> changes his stance on Constructor Over-Injection from <em>anti-pattern</em> to
the more palatable <em>code smell</em>. In this post I introduce the concept of an <strong>Aggregate
Service</strong> and outline a refactoring that addresses this code smell.
</p>
        <p>
If I should extract a core message from Jeffrey Palermo’s blog post it would be that
it’s a code smell if you have a class that takes too many dependencies in its constructor.
</p>
        <p>
I can only agree, but only so far as it’s a code smell. However, it has nothing to
do with DI in general or <strong>Constructor Injection</strong> specifically. Rather,
it’s a smell that indicates a violation of the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> (SRP). Let’s review the example constructor:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IAccountsReceivable\cf0  receivable,\par ??                      \cf4 IRateExchange\cf0  exchange,\par ??                      \cf4 IUserContext\cf0  userContext)}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> OrderProcessor(<span style="color: #2b91af">IOrderValidator</span> validator,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IOrderShipper</span> shipper,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IAccountsReceivable</span> receivable,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IRateExchange</span> exchange,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IUserContext</span> userContext)</pre>
        </div>
        <p>
In this version, I even added IOrderShipper back in <a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx">as
I described in my earlier post</a>. Surely, five constructor parameters are too many.
</p>
        <p>
          <em>
            <strong>Constructor Injection</strong> makes SRP violations glaringly obvious.</em>
        </p>
        <p>
What’s not to like? My personal threshold lies somewhere around 3-4 constructor parameters,
so whenever I hit three, I start to consider if I could perhaps aggregate some of
the dependencies into a new type.
</p>
        <p>
I call such a type an <strong>Aggregate Service</strong>. It’s closely related to <a href="http://www.refactoring.com/catalog/introduceParameterObject.html">Parameter
Objects</a>, but the main difference is that a <strong>Parameter Object</strong> only
moves the parameters to a common root, while an <strong>Aggregate Service</strong> hides
the aggregate behavior behind a new abstraction. While the <strong>Aggregate Service</strong> may
start its life as a result of a pure mechanistic refactoring, it often turns out that
the extracted behavior represents a Domain Concept in its own right. Congratulations:
you’ve just move a little closer to adhering to the SRP!
</p>
        <p>
Let’s look at Jeffrey Palermo’s OrderProcessor example. The core implementation of
the class is reproduced here (recall that in my version, IOrderShipper is also an
injected dependency):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf4 SuccessResult\cf0  Process(\cf4 Order\cf0  order)\par ??\{\par ??    \cf1 bool\cf0  isValid = _validator.Validate(order);\par ??    \cf1 if\cf0  (isValid)\par ??    \{\par ??        Collect(order);\par ??        _shipper.Ship(order);\par ??    \}\par ??\par ??    \cf1 return\cf0  CreateStatus(isValid);\par ??\}\par ??\par ??\cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??    \cf4 Price\cf0  price = order.GetPrice(_exchange, _userContext);\par ??    _receivable.Collect(user, price);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">SuccessResult</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">bool</span> isValid
= _validator.Validate(order);</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (isValid)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        Collect(order);</pre>
          <pre style="margin: 0px">        _shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> CreateStatus(isValid);</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">User</span> user
= _userContext.GetCurrentUser();</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Price</span> price
= order.GetPrice(_exchange, _userContext);</pre>
          <pre style="margin: 0px">    _receivable.Collect(user, price);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
If you examine the code it should quickly become apparent that the Collect method
encapsulates a cluster of dependencies: IAccountsReceivable, IRateExchange and IUserContext.
In this case it’s pretty obvious because they are already encapsulated in a single
private method. In real production code, you may need to perform a series of internal
refactorings before a pattern starts to emerge and you can extract an interface that
aggregates several dependencies.
</p>
        <p>
Now that we have identified the cluster of dependencies, we can extract an interface
that closely resembles the Collect method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 void\cf0  Collect(\cf4 Order\cf0  order);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IOrderCollector</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In lieu of a better name, I simply chose to call it IOrderCollector, but what’s interesting
about extracting <strong>Aggregate Services</strong> is that over time, they often
turn out to be previously <em>implicit</em> Domain Concepts that we have now dragged
out in the open and made <em>explicit</em>.
</p>
        <p>
We can now inject IOrderCollector into OrderProcessor and change the implementation
of the private Collect method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    _collector.Collect(order);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    _collector.Collect(order);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Next, we can remove the redundant dependencies, leaving us with this constructor:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IOrderCollector\cf0  collector)}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> OrderProcessor(<span style="color: #2b91af">IOrderValidator</span> validator,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IOrderShipper</span> shipper,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IOrderCollector</span> collector)</pre>
        </div>
        <p>
With three constructor parameters it’s much more acceptable, but we can always consider
repeating the procedure and extract a new <strong>Aggregate Service</strong> that
aggregates IOrderShipper and IOrderCollector.
</p>
        <p>
The original behavior from the Collect method is still required, but is now implemented
in the OrderCollector class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 OrderCollector\cf0  : \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IUserContext\cf0  _userContext;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IRateExchange\cf0  _exchange;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IAccountsReceivable\cf0  _receivable;\par ??\par ??    \cf1 public\cf0  OrderCollector(\cf4 IAccountsReceivable\cf0  receivable,\par ??                          \cf4 IRateExchange\cf0  exchange,\par ??                          \cf4 IUserContext\cf0  userContext)\par ??    \{\par ??        _receivable = receivable;\par ??        _exchange = exchange;\par ??        _userContext = userContext;\par ??    \}\par ??\par ??\cf1     #region\cf0  IOrderCollector Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??        \cf4 Price\cf0  price = \par ??            order.GetPrice(_exchange, _userContext);\par ??        _receivable.Collect(user, price);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">OrderCollector</span> : <span style="color: #2b91af">IOrderCollector</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IUserContext</span> _userContext;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IRateExchange</span> _exchange;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IAccountsReceivable</span> _receivable;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> OrderCollector(<span style="color: #2b91af">IAccountsReceivable</span> receivable,</pre>
          <pre style="margin: 0px">                          <span style="color: #2b91af">IRateExchange</span> exchange,</pre>
          <pre style="margin: 0px">                          <span style="color: #2b91af">IUserContext</span> userContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        _receivable = receivable;</pre>
          <pre style="margin: 0px">        _exchange = exchange;</pre>
          <pre style="margin: 0px">        _userContext = userContext;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IOrderCollector Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">User</span> user
= _userContext.GetCurrentUser();</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Price</span> price
= </pre>
          <pre style="margin: 0px">            order.GetPrice(_exchange, _userContext);</pre>
          <pre style="margin: 0px">        _receivable.Collect(user, price);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Here’s another class with three constructor parameters, which falls within the reasonable
range. However, once again, we can begin to consider whether the interaction between
IUserContext and the Order could be better modeled.
</p>
        <p>
In outline form, the <em>Introduce Aggregate Service</em> refactoring follows these
steps:
</p>
        <ol>
          <li>
Analyze how dependencies interact to identify clusters of behavior. 
</li>
          <li>
Extract an interface from these clusters. 
</li>
          <li>
Copy the original implementation to a class that implements the new interface. 
</li>
          <li>
Inject the new interface into the consumer. 
</li>
          <li>
Replace the original implementation with a call the new dependency. 
</li>
          <li>
Remove the redundant dependencies. 
</li>
          <li>
Rinse and repeat :)</li>
        </ol>
        <p>
The beauty of <strong>Aggregate Services</strong> is that we can keep wrapping one <strong>Aggregate
Service</strong> in new <strong>Aggregate Services</strong> to define more and more
coarse-grained building blocks as we get closer and closer to the application boundary.
</p>
        <p>
Keeping each class and its dependencies to simple interactions also makes it much
easier to unit test all of them because none of them do anything particularly complex.
</p>
        <p>
Adhering strictly to <strong>Constructor Injection</strong> makes it easy to see when
one violates the SRP and should refactor to an <strong>Aggregate Service</strong>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5" />
      </body>
      <title>Refactoring to Aggregate Services</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</guid>
      <link>http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx</link>
      <pubDate>Tue, 02 Feb 2010 20:56:44 GMT</pubDate>
      <description>&lt;p&gt;
In a &lt;a href="http://jeffreypalermo.com/blog/constructor-over-injection-smell-ndash-follow-up/"&gt;follow-up&lt;/a&gt; to
his &lt;a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/"&gt;earlier
post on Constructor Over-Injection&lt;/a&gt;, &lt;a href="http://jeffreypalermo.com/"&gt;Jeffrey
Palermo&lt;/a&gt; changes his stance on Constructor Over-Injection from &lt;em&gt;anti-pattern&lt;/em&gt; to
the more palatable &lt;em&gt;code smell&lt;/em&gt;. In this post I introduce the concept of an &lt;strong&gt;Aggregate
Service&lt;/strong&gt; and outline a refactoring that addresses this code smell.
&lt;/p&gt;
&lt;p&gt;
If I should extract a core message from Jeffrey Palermo’s blog post it would be that
it’s a code smell if you have a class that takes too many dependencies in its constructor.
&lt;/p&gt;
&lt;p&gt;
I can only agree, but only so far as it’s a code smell. However, it has nothing to
do with DI in general or &lt;strong&gt;Constructor Injection&lt;/strong&gt; specifically. Rather,
it’s a smell that indicates a violation of the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt; (SRP). Let’s review the example constructor:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IAccountsReceivable\cf0  receivable,\par ??                      \cf4 IRateExchange\cf0  exchange,\par ??                      \cf4 IUserContext\cf0  userContext)}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; OrderProcessor(&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt; validator,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt; shipper,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IAccountsReceivable&lt;/span&gt; receivable,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IRateExchange&lt;/span&gt; exchange,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IUserContext&lt;/span&gt; userContext)&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this version, I even added IOrderShipper back in &lt;a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx"&gt;as
I described in my earlier post&lt;/a&gt;. Surely, five constructor parameters are too many.
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;&lt;strong&gt;Constructor Injection&lt;/strong&gt; makes SRP violations glaringly obvious.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
What’s not to like? My personal threshold lies somewhere around 3-4 constructor parameters,
so whenever I hit three, I start to consider if I could perhaps aggregate some of
the dependencies into a new type.
&lt;/p&gt;
&lt;p&gt;
I call such a type an &lt;strong&gt;Aggregate Service&lt;/strong&gt;. It’s closely related to &lt;a href="http://www.refactoring.com/catalog/introduceParameterObject.html"&gt;Parameter
Objects&lt;/a&gt;, but the main difference is that a &lt;strong&gt;Parameter Object&lt;/strong&gt; only
moves the parameters to a common root, while an &lt;strong&gt;Aggregate Service&lt;/strong&gt; hides
the aggregate behavior behind a new abstraction. While the &lt;strong&gt;Aggregate Service&lt;/strong&gt; may
start its life as a result of a pure mechanistic refactoring, it often turns out that
the extracted behavior represents a Domain Concept in its own right. Congratulations:
you’ve just move a little closer to adhering to the SRP!
&lt;/p&gt;
&lt;p&gt;
Let’s look at Jeffrey Palermo’s OrderProcessor example. The core implementation of
the class is reproduced here (recall that in my version, IOrderShipper is also an
injected dependency):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf4 SuccessResult\cf0  Process(\cf4 Order\cf0  order)\par ??\{\par ??    \cf1 bool\cf0  isValid = _validator.Validate(order);\par ??    \cf1 if\cf0  (isValid)\par ??    \{\par ??        Collect(order);\par ??        _shipper.Ship(order);\par ??    \}\par ??\par ??    \cf1 return\cf0  CreateStatus(isValid);\par ??\}\par ??\par ??\cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??    \cf4 Price\cf0  price = order.GetPrice(_exchange, _userContext);\par ??    _receivable.Collect(user, price);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SuccessResult&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;bool&lt;/span&gt; isValid
= _validator.Validate(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (isValid)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Collect(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; CreateStatus(isValid);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;User&lt;/span&gt; user
= _userContext.GetCurrentUser();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Price&lt;/span&gt; price
= order.GetPrice(_exchange, _userContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; _receivable.Collect(user, price);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
If you examine the code it should quickly become apparent that the Collect method
encapsulates a cluster of dependencies: IAccountsReceivable, IRateExchange and IUserContext.
In this case it’s pretty obvious because they are already encapsulated in a single
private method. In real production code, you may need to perform a series of internal
refactorings before a pattern starts to emerge and you can extract an interface that
aggregates several dependencies.
&lt;/p&gt;
&lt;p&gt;
Now that we have identified the cluster of dependencies, we can extract an interface
that closely resembles the Collect method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 void\cf0  Collect(\cf4 Order\cf0  order);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;interface&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In lieu of a better name, I simply chose to call it IOrderCollector, but what’s interesting
about extracting &lt;strong&gt;Aggregate Services&lt;/strong&gt; is that over time, they often
turn out to be previously &lt;em&gt;implicit&lt;/em&gt; Domain Concepts that we have now dragged
out in the open and made &lt;em&gt;explicit&lt;/em&gt;.
&lt;/p&gt;
&lt;p&gt;
We can now inject IOrderCollector into OrderProcessor and change the implementation
of the private Collect method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    _collector.Collect(order);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; _collector.Collect(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Next, we can remove the redundant dependencies, leaving us with this constructor:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IOrderCollector\cf0  collector)}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; OrderProcessor(&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt; validator,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt; shipper,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt; collector)&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With three constructor parameters it’s much more acceptable, but we can always consider
repeating the procedure and extract a new &lt;strong&gt;Aggregate Service&lt;/strong&gt; that
aggregates IOrderShipper and IOrderCollector.
&lt;/p&gt;
&lt;p&gt;
The original behavior from the Collect method is still required, but is now implemented
in the OrderCollector class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 OrderCollector\cf0  : \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IUserContext\cf0  _userContext;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IRateExchange\cf0  _exchange;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IAccountsReceivable\cf0  _receivable;\par ??\par ??    \cf1 public\cf0  OrderCollector(\cf4 IAccountsReceivable\cf0  receivable,\par ??                          \cf4 IRateExchange\cf0  exchange,\par ??                          \cf4 IUserContext\cf0  userContext)\par ??    \{\par ??        _receivable = receivable;\par ??        _exchange = exchange;\par ??        _userContext = userContext;\par ??    \}\par ??\par ??\cf1     #region\cf0  IOrderCollector Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??        \cf4 Price\cf0  price = \par ??            order.GetPrice(_exchange, _userContext);\par ??        _receivable.Collect(user, price);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderCollector&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IUserContext&lt;/span&gt; _userContext;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IRateExchange&lt;/span&gt; _exchange;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IAccountsReceivable&lt;/span&gt; _receivable;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; OrderCollector(&lt;span style="color: #2b91af"&gt;IAccountsReceivable&lt;/span&gt; receivable,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IRateExchange&lt;/span&gt; exchange,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IUserContext&lt;/span&gt; userContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _receivable = receivable;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _exchange = exchange;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _userContext = userContext;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IOrderCollector Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;User&lt;/span&gt; user
= _userContext.GetCurrentUser();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Price&lt;/span&gt; price
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; order.GetPrice(_exchange, _userContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _receivable.Collect(user, price);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Here’s another class with three constructor parameters, which falls within the reasonable
range. However, once again, we can begin to consider whether the interaction between
IUserContext and the Order could be better modeled.
&lt;/p&gt;
&lt;p&gt;
In outline form, the &lt;em&gt;Introduce Aggregate Service&lt;/em&gt; refactoring follows these
steps:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Analyze how dependencies interact to identify clusters of behavior. 
&lt;li&gt;
Extract an interface from these clusters. 
&lt;li&gt;
Copy the original implementation to a class that implements the new interface. 
&lt;li&gt;
Inject the new interface into the consumer. 
&lt;li&gt;
Replace the original implementation with a call the new dependency. 
&lt;li&gt;
Remove the redundant dependencies. 
&lt;li&gt;
Rinse and repeat :)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The beauty of &lt;strong&gt;Aggregate Services&lt;/strong&gt; is that we can keep wrapping one &lt;strong&gt;Aggregate
Service&lt;/strong&gt; in new &lt;strong&gt;Aggregate Services&lt;/strong&gt; to define more and more
coarse-grained building blocks as we get closer and closer to the application boundary.
&lt;/p&gt;
&lt;p&gt;
Keeping each class and its dependencies to simple interactions also makes it much
easier to unit test all of them because none of them do anything particularly complex.
&lt;/p&gt;
&lt;p&gt;
Adhering strictly to &lt;strong&gt;Constructor Injection&lt;/strong&gt; makes it easy to see when
one violates the SRP and should refactor to an &lt;strong&gt;Aggregate Service&lt;/strong&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=60c2b13b-fc87-413b-bf88-d66513dbeddb</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,60c2b13b-fc87-413b-bf88-d66513dbeddb.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,60c2b13b-fc87-413b-bf88-d66513dbeddb.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=60c2b13b-fc87-413b-bf88-d66513dbeddb</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> 1.0 is now available on
the CodePlex site! Compared to Release Candidate 2 there are no changes.
</p>
        <p>
The <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=38630">1.0
release page</a> has more details about this particular release, but essentially this
is RC2 promoted to release status.
</p>
        <p>
It's been almost a year since I started development on AutoFixture and I must say
that it has been an exciting and fulfilling experience! The API has evolved, but has
turned out to be surprisingly flexible, yet robust. I even had some positive surprises
along the way as it dawned on me that I could do new fancy things I hadn't originally
considered.
</p>
        <p>
If you use the Likeness feature (of which I have yet to write), you will run into <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=524901">this
bug in Visual Studio</a>. The bug is only in IntelliSense, so any code using Likeness
will compile and work just fine.
</p>
        <p>
While this release marks the end of AutoFixture's initial days, it also marks the
beginning of AutoFixture 2.0. I already have lots of plans for making it even more
extensible and powerful, as well as plans for utility libraries that integrate with,
say, Moq or Rhino Mocks. It's going to be an exciting new voyage!
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=60c2b13b-fc87-413b-bf88-d66513dbeddb" />
      </body>
      <title>AutoFixture 1.0</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,60c2b13b-fc87-413b-bf88-d66513dbeddb.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/27/AutoFixture10.aspx</link>
      <pubDate>Wed, 27 Jan 2010 22:54:58 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 1.0 is now available on
the CodePlex site! Compared to Release Candidate 2 there are no changes.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=38630"&gt;1.0
release page&lt;/a&gt; has more details about this particular release, but essentially this
is RC2 promoted to release status.
&lt;/p&gt;
&lt;p&gt;
It's been almost a year since I started development on AutoFixture and I must say
that it has been an exciting and fulfilling experience! The API has evolved, but has
turned out to be surprisingly flexible, yet robust. I even had some positive surprises
along the way as it dawned on me that I could do new fancy things I hadn't originally
considered.
&lt;/p&gt;
&lt;p&gt;
If you use the Likeness feature (of which I have yet to write), you will run into &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=524901"&gt;this
bug in Visual Studio&lt;/a&gt;. The bug is only in IntelliSense, so any code using Likeness
will compile and work just fine.
&lt;/p&gt;
&lt;p&gt;
While this release marks the end of AutoFixture's initial days, it also marks the
beginning of AutoFixture 2.0. I already have lots of plans for making it even more
extensible and powerful, as well as plans for utility libraries that integrate with,
say, Moq or Rhino Mocks. It's going to be an exciting new voyage!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=60c2b13b-fc87-413b-bf88-d66513dbeddb" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,60c2b13b-fc87-413b-bf88-d66513dbeddb.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=7458672f-201e-47c5-a203-593520b55b45</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=7458672f-201e-47c5-a203-593520b55b45</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a reaction to <a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings">Uncle
Bob</a>'s recent post on <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion">Dependency
Injection Inversion</a>, <a href="http://blog.cgdecker.com/">Colin Decker</a> writes
that he <a href="http://blog.cgdecker.com/2010/01/whats-issue-with-inject.html">doesn't
consider the use of the single Guice @Inject annotation particularly problematic</a>.
As I read it, the central argument is that
</p>
        <blockquote>
          <p>
annotations are not code. By themselves, they do nothing.
</p>
        </blockquote>
        <p>
I'll have to take that at face value, but if we translate this reasoning to .NET it
certainly holds true. Attributes don't do anything by themselves.
</p>
        <p>
I'm not aware of any DI Container for .NET that <em>requires</em> us to sprinkle attributes
all over our code to work (I don't consider <a href="http://mef.codeplex.com/">MEF</a> a
DI Container), but for the sake of argument, let's assume that such a container exists
(let's call it <em><a href="http://en.wikipedia.org/wiki/Hypodermic_needle">Needle</a></em>).
Would it be so bad if we had to liberally apply the Needle [Inject] attribute in large
parts of our code bases?
</p>
        <p>
Colin suggests <em>no</em>. As usual, my position is that it depends, but in most
cases I would consider it bad.
</p>
        <p>
If Needle is implemented like most libraries, InjectAttribute is just one of many
types that make up the entire API. Other types would include NeedleContainer and its
associated classes.
</p>
        <p>
Java annotations may work differently, but in .NET we need to reference a library
to apply one of its attributes. To apply the [Inject] attribute, we would have to
reference Needle, and herein lies the problem.
</p>
        <p>
Once Needle is referenced, it becomes much easier for a junior developer to accidentally
start directly using other parts of the Needle API. Particularly he or she may start
using Needle as a Service Locator. When that happens, Needle is no longer a passive
participant of the code, but a very active one, and it becomes much harder to separate
the code from the Container.
</p>
        <p>
To paraphrase Uncle Bob: <em>I don't want to write a Needle application.</em></p>
        <p>
We can't even protect ourselves from accidental usage by writing a <a href="http://blogs.msdn.com/gblock/archive/2008/05/05/prismshouldnotreferenceunity.aspx">convention-based
unit test</a> that fails if Needle is referenced by our code, because it <em>must</em> be
referenced for the [Inject] attribute to be applied.
</p>
        <p>
The point is that the attribute drags in a reference to the entire container, which
in my opinion is a bad thing.
</p>
        <p>
So when would it be less problematic?
</p>
        <p>
If Needle was implemented in such a way that InjectAttribute was defined in an assembly
that only contains that one type, and the rest of Needle was implemented in a different
assembly, the attribute wouldn't drag the rest of the container along.
</p>
        <p>
Whether this whole analysis makes sense at all in Java, and whether Guice is implemented
like that, I can't say, but in most cases I would consider even a single attribute
to be unacceptable pollution of my code base.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7458672f-201e-47c5-a203-593520b55b45" />
      </body>
      <title>What's so dangerous about a DI attribute?</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/27/WhatsSoDangerousAboutADIAttribute.aspx</link>
      <pubDate>Wed, 27 Jan 2010 19:36:34 GMT</pubDate>
      <description>&lt;p&gt;
In a reaction to &lt;a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings"&gt;Uncle
Bob&lt;/a&gt;'s recent post on &lt;a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion"&gt;Dependency
Injection Inversion&lt;/a&gt;, &lt;a href="http://blog.cgdecker.com/"&gt;Colin Decker&lt;/a&gt; writes
that he &lt;a href="http://blog.cgdecker.com/2010/01/whats-issue-with-inject.html"&gt;doesn't
consider the use of the single Guice @Inject annotation particularly problematic&lt;/a&gt;.
As I read it, the central argument is that
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
annotations are not code. By themselves, they do nothing.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
I'll have to take that at face value, but if we translate this reasoning to .NET it
certainly holds true. Attributes don't do anything by themselves.
&lt;/p&gt;
&lt;p&gt;
I'm not aware of any DI Container for .NET that &lt;em&gt;requires&lt;/em&gt; us to sprinkle attributes
all over our code to work (I don't consider &lt;a href="http://mef.codeplex.com/"&gt;MEF&lt;/a&gt; a
DI Container), but for the sake of argument, let's assume that such a container exists
(let's call it &lt;em&gt;&lt;a href="http://en.wikipedia.org/wiki/Hypodermic_needle"&gt;Needle&lt;/a&gt;&lt;/em&gt;).
Would it be so bad if we had to liberally apply the Needle [Inject] attribute in large
parts of our code bases?
&lt;/p&gt;
&lt;p&gt;
Colin suggests &lt;em&gt;no&lt;/em&gt;. As usual, my position is that it depends, but in most
cases I would consider it bad.
&lt;/p&gt;
&lt;p&gt;
If Needle is implemented like most libraries, InjectAttribute is just one of many
types that make up the entire API. Other types would include NeedleContainer and its
associated classes.
&lt;/p&gt;
&lt;p&gt;
Java annotations may work differently, but in .NET we need to reference a library
to apply one of its attributes. To apply the [Inject] attribute, we would have to
reference Needle, and herein lies the problem.
&lt;/p&gt;
&lt;p&gt;
Once Needle is referenced, it becomes much easier for a junior developer to accidentally
start directly using other parts of the Needle API. Particularly he or she may start
using Needle as a Service Locator. When that happens, Needle is no longer a passive
participant of the code, but a very active one, and it becomes much harder to separate
the code from the Container.
&lt;/p&gt;
&lt;p&gt;
To paraphrase Uncle Bob: &lt;em&gt;I don't want to write a Needle application.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
We can't even protect ourselves from accidental usage by writing a &lt;a href="http://blogs.msdn.com/gblock/archive/2008/05/05/prismshouldnotreferenceunity.aspx"&gt;convention-based
unit test&lt;/a&gt; that fails if Needle is referenced by our code, because it &lt;em&gt;must&lt;/em&gt; be
referenced for the [Inject] attribute to be applied.
&lt;/p&gt;
&lt;p&gt;
The point is that the attribute drags in a reference to the entire container, which
in my opinion is a bad thing.
&lt;/p&gt;
&lt;p&gt;
So when would it be less problematic?
&lt;/p&gt;
&lt;p&gt;
If Needle was implemented in such a way that InjectAttribute was defined in an assembly
that only contains that one type, and the rest of Needle was implemented in a different
assembly, the attribute wouldn't drag the rest of the container along.
&lt;/p&gt;
&lt;p&gt;
Whether this whole analysis makes sense at all in Java, and whether Guice is implemented
like that, I can't say, but in most cases I would consider even a single attribute
to be unacceptable pollution of my code base.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7458672f-201e-47c5-a203-593520b55b45" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2aef793d-f3f4-479f-9144-b26e093f8376</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2aef793d-f3f4-479f-9144-b26e093f8376</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Reacting to my <a href="http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx">previous
post</a>, <a href="http://kozmic.pl/Default.aspx">Krzysztof Koźmic</a> was so kind
to point out to me that I really should be using an IWindsorInstaller instead of writing
the registration code in a static helper method (it <em>did</em> make me cringe a
bit).
</p>
        <p>
As it turns out, IWindsorInstaller is not a particularly well-described feature of <a href="http://castleproject.org/container/index.html">Castle
Windsor</a>, so here's a quick introduction. Fortunately, it is very easy to understand.
</p>
        <p>
The idea is simply to package configuration code in reusable modules (just like the
Guice modules from <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion">Uncle
Bob's post</a>).
</p>
        <p>
Refactoring the bootstrap code from my previous post, I can now move all the container
configuration code into a reusable module:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">BillingContainerInstaller</span> : <span style="color: #2b91af">IWindsorInstaller</span></p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
            <span style="color: blue">    #region</span> IWindsorInstaller Members
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span><span style="color: blue">void</span> Install(<span style="color: #2b91af">IWindsorContainer</span> container,
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">IConfigurationStore</span> store)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        container.AddComponent&lt;<span style="color: #2b91af">TransactionLog</span>, 
</p>
          <p style="margin: 0px">
            <span style="color: #2b91af">DatabaseTransactionLog</span>&gt;();
</p>
          <p style="margin: 0px">
        container.AddComponent&lt;<span style="color: #2b91af">CreditCardProcessor</span>,
</p>
          <p style="margin: 0px">
            <span style="color: #2b91af">MyCreditCardProcessor</span>&gt;();
</p>
          <p style="margin: 0px">
        container.AddComponent&lt;<span style="color: #2b91af">BillingService</span>&gt;();
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
            <span style="color: blue">    #endregion</span>
          </p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
While I was at it, I also changed from the fluent registration API to the generic
registration methods as I didn't really need the full API, but I could have left it
as it was.
</p>
        <p>
BillingContainerInstaller implements IWindsorInstaller, and I can now configure my
container instance like this:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">var</span> container = <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();
</p>
          <p style="margin: 0px">
container.Install(<span style="color: blue">new</span><span style="color: #2b91af">BillingContainerInstaller</span>());
</p>
        </div>
        <p>
The Install method takes a parameter array of IWindsorInstaller instances, so you
can pass as many as you'd like.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2aef793d-f3f4-479f-9144-b26e093f8376" />
      </body>
      <title>IWindsorInstaller</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/26/IWindsorInstaller.aspx</link>
      <pubDate>Tue, 26 Jan 2010 19:24:51 GMT</pubDate>
      <description>&lt;p&gt;
Reacting to my &lt;a href="http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx"&gt;previous
post&lt;/a&gt;, &lt;a href="http://kozmic.pl/Default.aspx"&gt;Krzysztof Koźmic&lt;/a&gt; was so kind
to point out to me that I really should be using an IWindsorInstaller instead of writing
the registration code in a static helper method (it &lt;em&gt;did&lt;/em&gt; make me cringe a
bit).
&lt;/p&gt;
&lt;p&gt;
As it turns out, IWindsorInstaller is not a particularly well-described feature of &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt;, so here's a quick introduction. Fortunately, it is very easy to understand.
&lt;/p&gt;
&lt;p&gt;
The idea is simply to package configuration code in reusable modules (just like the
Guice modules from &lt;a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion"&gt;Uncle
Bob's post&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
Refactoring the bootstrap code from my previous post, I can now move all the container
configuration code into a reusable module:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;BillingContainerInstaller&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IWindsorInstaller&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #region&lt;/span&gt; IWindsorInstaller Members
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Install(&lt;span style="color: #2b91af"&gt;IWindsorContainer&lt;/span&gt; container,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IConfigurationStore&lt;/span&gt; store)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddComponent&amp;lt;&lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt;, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DatabaseTransactionLog&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddComponent&amp;lt;&lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt;,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MyCreditCardProcessor&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddComponent&amp;lt;&lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #endregion&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
While I was at it, I also changed from the fluent registration API to the generic
registration methods as I didn't really need the full API, but I could have left it
as it was.
&lt;/p&gt;
&lt;p&gt;
BillingContainerInstaller implements IWindsorInstaller, and I can now configure my
container instance like this:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;var&lt;/span&gt; container = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
container.Install(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;BillingContainerInstaller&lt;/span&gt;());
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
The Install method takes a parameter array of IWindsorInstaller instances, so you
can pass as many as you'd like.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2aef793d-f3f4-479f-9144-b26e093f8376" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=224fbfca-7f4a-4d5c-a713-8db5e0720fe2</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=224fbfca-7f4a-4d5c-a713-8db5e0720fe2</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
About a week ago <a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings">Uncle
Bob</a> published a post on <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion">Dependency
Injection Inversion</a> that caused quite a stir in the tiny part of the .NET community
I usually pretend to hang out with. Twitter was alive with much debate, but <a href="http://ayende.com/Blog/Default.aspx">Ayende</a> seems
to <a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx">sum
up</a> the .NET DI community's sentiment pretty well:
</p>
        <blockquote>
          <p>
if this is a typical example of IoC usage in the Java world, then [Uncle Bob] should
peek over the fence to see how IoC is commonly implemented in the .Net space
</p>
        </blockquote>
        <p>
Despite having initially left a more or less positive note to Uncle Bob's post, after
having re-read it carefully, I am beginning to think the same, but instead of just <em>telling</em> everyone
how much greener the grass is on the .NET side, let me <em>show</em> you.
</p>
        <p>
First of all, let's translate Uncle Bob's BillingService to C#:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">BillingService</span>
          </p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">CreditCardProcessor</span> processor;
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">TransactionLog</span> transactionLog;
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span> BillingService(<span style="color: #2b91af">CreditCardProcessor</span> processor,
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">TransactionLog</span> transactionLog)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (processor
== <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"processor"</span>);
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (transactionLog
== <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"transactionLog"</span>);
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.processor
= processor;
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.transactionLog
= transactionLog;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span><span style="color: blue">void</span> ProcessCharge(<span style="color: blue">int</span> amount, <span style="color: blue">string</span> id)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> approval
= <span style="color: blue">this</span>.processor.Approve(amount, id);
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.transactionLog.Log(<span style="color: blue">string</span>.Format(
</p>
          <p style="margin: 0px">
            <span style="color: #a31515">"Transaction
by {0} for {1} {2}"</span>, id, amount, 
</p>
          <p style="margin: 0px">
            <span style="color: blue">this</span>.GetApprovalCode(approval)));
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">string</span> GetApprovalCode(<span style="color: blue">bool</span> approval)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">return</span> approval
? <span style="color: #a31515">"approved"</span> : <span style="color: #a31515">"denied"</span>;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
It's nice how easy it is to translate Java code to C#, but apart from casing and other
minor deviations, let's focus on the main difference. I've added Guard Clauses to
protect the injected dependencies against null values as I consider this an essential
and required part of <strong>Constructor Injection</strong> – I think Uncle Bob should
have added those as well, but he might have omitted them for brevity.
</p>
        <p>
If you disregard the Guard Clauses, the C# version is a logical line of code shorter
than the Java version because it has no DI attribute like Guice's @Inject.
</p>
        <p>
Does this mean that we can't do DI with the C# version of BillingService? Uncle Bob
seems to imply that we can do <em>Dependency Inversion</em>, but not <em>Dependency
Injection</em> - or is it the other way around? I can't really make head or tails
of that part of the post…
</p>
        <p>
The interesting part is that in .NET, <em>there's no difference!</em> We can use DI
Containers with the BillingService without sprinkling DI attributes all over our code
base. The BillingService class has no reference to any DI Container.
</p>
        <p>
It does, however, use the central DI pattern <strong>Constructor Injection</strong>.
.NET DI Containers know all about this pattern, and with .NET's static type system
they know all they need to know to wire dependencies up correctly. (I thought that
Java had a static type system as well, but perhaps I am mistaken.) The .NET DI Containers
will figure it out for you – you don't have to explicitly tell them how to invoke
a constructor with two parameters.
</p>
        <p>
We can write an entire application by using <strong>Constructor Injection</strong> and
stacking dependencies <em>without ever referencing a container!</em></p>
        <p>
Like the Lean concept of the <em>Last Responsible Moment</em>, we can wait until the
application's entry point to decide how we will wire up the dependencies.
</p>
        <p>
As Uncle Bob suggests, we can use <strong>Poor Man's DI</strong> and manually create
the dependencies directly in Main, but as <a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx">Ayende
correctly observes</a>, that only looks like an attractive alternative because the
example is so simple. For complex dependency graphs, a DI Container is a much better
choice.
</p>
        <p>
With the C# version of BillingService, which DI Container must we select?
</p>
        <p>
It doesn't matter: we can choose whichever one we would like because we have been
following patterns instead of using a framework.
</p>
        <p>
Here's an example of an implementation of Main using <a href="http://castleproject.org/">Castle
Windsor</a>:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Main(<span style="color: blue">string</span>[]
args)
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> container = <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">Program</span>.Configure(container);
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> billingService =
</p>
          <p style="margin: 0px">
        container.Resolve&lt;<span style="color: #2b91af">BillingService</span>&gt;();
</p>
          <p style="margin: 0px">
    billingService.ProcessCharge(<span style="color: #a52a2a">2034</span>, <span style="color: #a31515">"Bob"</span>);
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
This looks a lot like Uncle Bob's first Guice example, but instead of injecting a
BillingModule into the container, we can configure it inline or in a helper method:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Configure(<span style="color: #2b91af">WindsorContainer</span> container)
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    container.Register(<span style="color: #2b91af">Component</span></p>
          <p style="margin: 0px">
        .For&lt;<span style="color: #2b91af">TransactionLog</span>&gt;()
</p>
          <p style="margin: 0px">
        .ImplementedBy&lt;<span style="color: #2b91af">DatabaseTransactionLog</span>&gt;());
</p>
          <p style="margin: 0px">
    container.Register(<span style="color: #2b91af">Component</span></p>
          <p style="margin: 0px">
        .For&lt;<span style="color: #2b91af">CreditCardProcessor</span>&gt;()
</p>
          <p style="margin: 0px">
        .ImplementedBy&lt;<span style="color: #2b91af">MyCreditCardProcessor</span>&gt;());
</p>
          <p style="margin: 0px">
    container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">BillingService</span>&gt;());
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
This corresponds more or less to the Guice-specific BillingModule, although Windsor
also requires us to register the concrete BillingService as a component (this last
step varies a bit from DI Container to DI Container – it is, for example, redundant
in <a href="http://www.codeplex.com/unity">Unity</a>).
</p>
        <p>
Imagine that in the future we want to rewire this program to use a different DI Container.
The only piece of code we need to change is this <strong>Composition Root</strong>.
We need to change the container declaration and configuration and then we are ready
to use a different DI Container.
</p>
        <p>
The bottom line is that Uncle Bob's <em>Dependency Injection Inversion</em> is redundant
in .NET. Just use a few well-known design patterns and principles and you can write
entire applications with DI-friendly, DI-agnostic code bases.
</p>
        <p>
I recently posted a <a href="http://stackoverflow.com/questions/2045904/dependency-inject-di-friendly-library/2047657#2047657">first
take on guidelines for writing DI-agnostic code</a>. I plan to evolve these guiding
principles and make them a part of <a href="http://www.manning.com/seemann">my upcoming
book</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=224fbfca-7f4a-4d5c-a713-8db5e0720fe2" />
      </body>
      <title>Dependency Injection Inversion in .NET</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx</link>
      <pubDate>Mon, 25 Jan 2010 20:48:27 GMT</pubDate>
      <description>&lt;p&gt;
About a week ago &lt;a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings"&gt;Uncle
Bob&lt;/a&gt; published a post on &lt;a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion"&gt;Dependency
Injection Inversion&lt;/a&gt; that caused quite a stir in the tiny part of the .NET community
I usually pretend to hang out with. Twitter was alive with much debate, but &lt;a href="http://ayende.com/Blog/Default.aspx"&gt;Ayende&lt;/a&gt; seems
to &lt;a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx"&gt;sum
up&lt;/a&gt; the .NET DI community's sentiment pretty well:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
if this is a typical example of IoC usage in the Java world, then [Uncle Bob] should
peek over the fence to see how IoC is commonly implemented in the .Net space
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Despite having initially left a more or less positive note to Uncle Bob's post, after
having re-read it carefully, I am beginning to think the same, but instead of just &lt;em&gt;telling&lt;/em&gt; everyone
how much greener the grass is on the .NET side, let me &lt;em&gt;show&lt;/em&gt; you.
&lt;/p&gt;
&lt;p&gt;
First of all, let's translate Uncle Bob's BillingService to C#:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt; processor;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt; transactionLog;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; BillingService(&lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt; processor,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt; transactionLog)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (processor
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"processor"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (transactionLog
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"transactionLog"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.processor
= processor;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.transactionLog
= transactionLog;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ProcessCharge(&lt;span style="color: blue"&gt;int&lt;/span&gt; amount, &lt;span style="color: blue"&gt;string&lt;/span&gt; id)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; approval
= &lt;span style="color: blue"&gt;this&lt;/span&gt;.processor.Approve(amount, id);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.transactionLog.Log(&lt;span style="color: blue"&gt;string&lt;/span&gt;.Format(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"Transaction
by {0} for {1} {2}"&lt;/span&gt;, id, amount, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.GetApprovalCode(approval)));
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; GetApprovalCode(&lt;span style="color: blue"&gt;bool&lt;/span&gt; approval)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; approval
? &lt;span style="color: #a31515"&gt;"approved"&lt;/span&gt; : &lt;span style="color: #a31515"&gt;"denied"&lt;/span&gt;;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
It's nice how easy it is to translate Java code to C#, but apart from casing and other
minor deviations, let's focus on the main difference. I've added Guard Clauses to
protect the injected dependencies against null values as I consider this an essential
and required part of &lt;strong&gt;Constructor Injection&lt;/strong&gt; – I think Uncle Bob should
have added those as well, but he might have omitted them for brevity.
&lt;/p&gt;
&lt;p&gt;
If you disregard the Guard Clauses, the C# version is a logical line of code shorter
than the Java version because it has no DI attribute like Guice's @Inject.
&lt;/p&gt;
&lt;p&gt;
Does this mean that we can't do DI with the C# version of BillingService? Uncle Bob
seems to imply that we can do &lt;em&gt;Dependency Inversion&lt;/em&gt;, but not &lt;em&gt;Dependency
Injection&lt;/em&gt; - or is it the other way around? I can't really make head or tails
of that part of the post…
&lt;/p&gt;
&lt;p&gt;
The interesting part is that in .NET, &lt;em&gt;there's no difference!&lt;/em&gt; We can use DI
Containers with the BillingService without sprinkling DI attributes all over our code
base. The BillingService class has no reference to any DI Container.
&lt;/p&gt;
&lt;p&gt;
It does, however, use the central DI pattern &lt;strong&gt;Constructor Injection&lt;/strong&gt;.
.NET DI Containers know all about this pattern, and with .NET's static type system
they know all they need to know to wire dependencies up correctly. (I thought that
Java had a static type system as well, but perhaps I am mistaken.) The .NET DI Containers
will figure it out for you – you don't have to explicitly tell them how to invoke
a constructor with two parameters.
&lt;/p&gt;
&lt;p&gt;
We can write an entire application by using &lt;strong&gt;Constructor Injection&lt;/strong&gt; and
stacking dependencies &lt;em&gt;without ever referencing a container!&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
Like the Lean concept of the &lt;em&gt;Last Responsible Moment&lt;/em&gt;, we can wait until the
application's entry point to decide how we will wire up the dependencies.
&lt;/p&gt;
&lt;p&gt;
As Uncle Bob suggests, we can use &lt;strong&gt;Poor Man's DI&lt;/strong&gt; and manually create
the dependencies directly in Main, but as &lt;a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx"&gt;Ayende
correctly observes&lt;/a&gt;, that only looks like an attractive alternative because the
example is so simple. For complex dependency graphs, a DI Container is a much better
choice.
&lt;/p&gt;
&lt;p&gt;
With the C# version of BillingService, which DI Container must we select?
&lt;/p&gt;
&lt;p&gt;
It doesn't matter: we can choose whichever one we would like because we have been
following patterns instead of using a framework.
&lt;/p&gt;
&lt;p&gt;
Here's an example of an implementation of Main using &lt;a href="http://castleproject.org/"&gt;Castle
Windsor&lt;/a&gt;:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[]
args)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; container = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Program&lt;/span&gt;.Configure(container);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; billingService =
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; billingService.ProcessCharge(&lt;span style="color: #a52a2a"&gt;2034&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"Bob"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
This looks a lot like Uncle Bob's first Guice example, but instead of injecting a
BillingModule into the container, we can configure it inline or in a helper method:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Configure(&lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt; container)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt;&amp;gt;()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;DatabaseTransactionLog&lt;/span&gt;&amp;gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt;&amp;gt;()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;MyCreditCardProcessor&lt;/span&gt;&amp;gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;&amp;gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
This corresponds more or less to the Guice-specific BillingModule, although Windsor
also requires us to register the concrete BillingService as a component (this last
step varies a bit from DI Container to DI Container – it is, for example, redundant
in &lt;a href="http://www.codeplex.com/unity"&gt;Unity&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
Imagine that in the future we want to rewire this program to use a different DI Container.
The only piece of code we need to change is this &lt;strong&gt;Composition Root&lt;/strong&gt;.
We need to change the container declaration and configuration and then we are ready
to use a different DI Container.
&lt;/p&gt;
&lt;p&gt;
The bottom line is that Uncle Bob's &lt;em&gt;Dependency Injection Inversion&lt;/em&gt; is redundant
in .NET. Just use a few well-known design patterns and principles and you can write
entire applications with DI-friendly, DI-agnostic code bases.
&lt;/p&gt;
&lt;p&gt;
I recently posted a &lt;a href="http://stackoverflow.com/questions/2045904/dependency-inject-di-friendly-library/2047657#2047657"&gt;first
take on guidelines for writing DI-agnostic code&lt;/a&gt;. I plan to evolve these guiding
principles and make them a part of &lt;a href="http://www.manning.com/seemann"&gt;my upcoming
book&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=224fbfca-7f4a-4d5c-a713-8db5e0720fe2" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=18f01f5d-d73e-45b0-bb2b-03890b43256b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,18f01f5d-d73e-45b0-bb2b-03890b43256b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,18f01f5d-d73e-45b0-bb2b-03890b43256b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=18f01f5d-d73e-45b0-bb2b-03890b43256b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> 1.0 Release Candidate 2
is now available on the CodePlex site! Compared to Release Candidate 1 there are very
few changes, but the test period uncovered the need for a few extra methods on a recent
addition to the library. RC2 contains these additional methods.
</p>
        <p>
This resets the clock for the Release Candidate trial period. Key users have a chance
to veto this release until a week from now. If no-one complains within that period,
we will promote RC2 to version 1.0.
</p>
        <p>
The <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=39161">RC2
release page</a> has more details about this particular release.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=18f01f5d-d73e-45b0-bb2b-03890b43256b" />
      </body>
      <title>AutoFixture 1.0 RC2</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,18f01f5d-d73e-45b0-bb2b-03890b43256b.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/20/AutoFixture10RC2.aspx</link>
      <pubDate>Wed, 20 Jan 2010 22:59:39 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 1.0 Release Candidate 2
is now available on the CodePlex site! Compared to Release Candidate 1 there are very
few changes, but the test period uncovered the need for a few extra methods on a recent
addition to the library. RC2 contains these additional methods.
&lt;/p&gt;
&lt;p&gt;
This resets the clock for the Release Candidate trial period. Key users have a chance
to veto this release until a week from now. If no-one complains within that period,
we will promote RC2 to version 1.0.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=39161"&gt;RC2
release page&lt;/a&gt; has more details about this particular release.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=18f01f5d-d73e-45b0-bb2b-03890b43256b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,18f01f5d-d73e-45b0-bb2b-03890b43256b.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=d191b73f-d5e8-462e-969c-0a005fc602c6</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,d191b73f-d5e8-462e-969c-0a005fc602c6.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,d191b73f-d5e8-462e-969c-0a005fc602c6.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=d191b73f-d5e8-462e-969c-0a005fc602c6</wfw:commentRss>
      <slash:comments>7</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
My <a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx">previous
post</a> led to this comment by <a href="http://haacked.com/">Phil Haack</a>:
</p>
        <blockquote>
          <p>
Your LazyOrderShipper directly instantiates an OrderShipper. What about the dependencies
that OrderShipper might require? What if those dependencies are costly?
</p>
        </blockquote>
        <p>
I didn't want to make my original example more complex than necessary to get the point
across, so I admit that I made it a bit simpler than I might have liked. However,
the issue is easily solved by enabling DI for the LazyOrderShipper itself.
</p>
        <p>
As always, when the dependency's lifetime may be shorter than the consumer, the solution
is to inject (via the constructor!) an Abstract Factory, as this modification of LazyOrderShipper
shows:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LazyOrderShipper2\cf0  : \cf4 IOrderShipper\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IOrderShipperFactory\cf0  factory;\par ??    \cf1 private\cf0  \cf4 IOrderShipper\cf0  shipper;\par ??\par ??    \cf1 public\cf0  LazyOrderShipper2(\cf4 IOrderShipperFactory\cf0  factory)\par ??    \{\par ??        \cf1 if\cf0  (factory == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "factory"\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .factory = factory;\par ??    \}\par ??\par ??\cf1     #region\cf0  IOrderShipper Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Ship(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf1 if\cf0  (\cf1 this\cf0 .shipper == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 this\cf0 .shipper = \cf1 this\cf0 .factory.Create();\par ??        \}\par ??        \cf1 this\cf0 .shipper.Ship(order);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">LazyOrderShipper2</span> : <span style="color: #2b91af">IOrderShipper</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IOrderShipperFactory</span> factory;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: #2b91af">IOrderShipper</span> shipper;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> LazyOrderShipper2(<span style="color: #2b91af">IOrderShipperFactory</span> factory)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (factory
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"factory"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.factory
= factory;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IOrderShipper Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Ship(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (<span style="color: blue">this</span>.shipper
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.shipper
= <span style="color: blue">this</span>.factory.Create();</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
But, doesn't that reintroduce the OrderShipperFactory that I earlier claimed was a
bad design?
</p>
        <p>
No, it doesn't, because this IOrderShipperFactory doesn't rely on static configuration.
The other point is that while we do have an IOrderShipperFactory, the original design
of OrderProcessor is unchanged (and thus blissfully unaware of the existence of this
Abstract Factory).
</p>
        <p>
The lifetime of the various dependencies is completely decoupled from the components
themselves, and this is as it should be with DI.
</p>
        <p>
This version of LazyOrderShipper is more reusable because it doesn't rely on any particular
implementation of OrderShipper – it can Lazily create any IOrderShipper.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d191b73f-d5e8-462e-969c-0a005fc602c6" />
      </body>
      <title>Enabling DI for Lazy Components</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,d191b73f-d5e8-462e-969c-0a005fc602c6.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/20/EnablingDIForLazyComponents.aspx</link>
      <pubDate>Wed, 20 Jan 2010 18:08:36 GMT</pubDate>
      <description>&lt;p&gt;
My &lt;a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx"&gt;previous
post&lt;/a&gt; led to this comment by &lt;a href="http://haacked.com/"&gt;Phil Haack&lt;/a&gt;:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Your LazyOrderShipper directly instantiates an OrderShipper. What about the dependencies
that OrderShipper might require? What if those dependencies are costly?
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
I didn't want to make my original example more complex than necessary to get the point
across, so I admit that I made it a bit simpler than I might have liked. However,
the issue is easily solved by enabling DI for the LazyOrderShipper itself.
&lt;/p&gt;
&lt;p&gt;
As always, when the dependency's lifetime may be shorter than the consumer, the solution
is to inject (via the constructor!) an Abstract Factory, as this modification of LazyOrderShipper
shows:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LazyOrderShipper2\cf0  : \cf4 IOrderShipper\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IOrderShipperFactory\cf0  factory;\par ??    \cf1 private\cf0  \cf4 IOrderShipper\cf0  shipper;\par ??\par ??    \cf1 public\cf0  LazyOrderShipper2(\cf4 IOrderShipperFactory\cf0  factory)\par ??    \{\par ??        \cf1 if\cf0  (factory == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "factory"\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .factory = factory;\par ??    \}\par ??\par ??\cf1     #region\cf0  IOrderShipper Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Ship(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf1 if\cf0  (\cf1 this\cf0 .shipper == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 this\cf0 .shipper = \cf1 this\cf0 .factory.Create();\par ??        \}\par ??        \cf1 this\cf0 .shipper.Ship(order);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LazyOrderShipper2&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IOrderShipperFactory&lt;/span&gt; factory;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt; shipper;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; LazyOrderShipper2(&lt;span style="color: #2b91af"&gt;IOrderShipperFactory&lt;/span&gt; factory)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (factory
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"factory"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.factory
= factory;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IOrderShipper Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Ship(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (&lt;span style="color: blue"&gt;this&lt;/span&gt;.shipper
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.shipper
= &lt;span style="color: blue"&gt;this&lt;/span&gt;.factory.Create();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
But, doesn't that reintroduce the OrderShipperFactory that I earlier claimed was a
bad design?
&lt;/p&gt;
&lt;p&gt;
No, it doesn't, because this IOrderShipperFactory doesn't rely on static configuration.
The other point is that while we do have an IOrderShipperFactory, the original design
of OrderProcessor is unchanged (and thus blissfully unaware of the existence of this
Abstract Factory).
&lt;/p&gt;
&lt;p&gt;
The lifetime of the various dependencies is completely decoupled from the components
themselves, and this is as it should be with DI.
&lt;/p&gt;
&lt;p&gt;
This version of LazyOrderShipper is more reusable because it doesn't rely on any particular
implementation of OrderShipper – it can Lazily create any IOrderShipper.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d191b73f-d5e8-462e-969c-0a005fc602c6" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,d191b73f-d5e8-462e-969c-0a005fc602c6.aspx</comments>
      <category>Dependency Injection</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=844f19d3-5b3b-4b1b-b9c9-f53059a5079f</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,844f19d3-5b3b-4b1b-b9c9-f53059a5079f.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,844f19d3-5b3b-4b1b-b9c9-f53059a5079f.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=844f19d3-5b3b-4b1b-b9c9-f53059a5079f</wfw:commentRss>
      <slash:comments>10</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://jeffreypalermo.com/">Jeffrey Palermo</a> recently posted a blog post
titled <a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/">Constructor
over-injection anti-pattern</a> – go read his post first if you want to be able to
follow my arguments.
</p>
        <p>
His point seems to be that Constructor Injection can be an anti-pattern if applied
too much, particularly if a consumer doesn't need a particular dependency in the majority
of cases.
</p>
        <p>
The problem is illustrated in this little code snippet:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 bool\cf0  isValid = _validator.Validate(order);  \par ??\cf1 if\cf0  (isValid) \par ??\{\par ??    _shipper.Ship(order);  \par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">bool</span> isValid
= _validator.Validate(order);  </pre>
          <pre style="margin: 0px">
            <span style="color: blue">if</span> (isValid) </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    _shipper.Ship(order);  </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
If the Validate method returns false often, the shipper dependency is never needed. 
</p>
        <p>
This, he argues, can lead to inefficiencies if the dependency is costly to create.
It's not a good thing to require a costly dependency if you are not going to use it
in a lot of cases.
</p>
        <p>
That sounds like a reasonable statement, but is it really? And is the proposed solution
a good solution?
</p>
        <p>
          <em>No, this isn't a reasonable statement, and the proposed solution isn't a good
solution.</em>
        </p>
        <p>
It would seem like there's a problem with Constructor Injection, but in reality the
problem is that it is being used incorrectly and in too constrained a way.
</p>
        <p>
The proposed solution is problematic because it involves tightly coupling the code
to OrderShipperFactory. This is more or less a specialized application of the Service
Locator anti-pattern.
</p>
        <p>
Consumers of OrderProcessor have no static type information to warn them that they
need to configure the OrderShipperFactory.CreationClosure static member - a completely
unrelated type. This may technically work, but creates a very developer-unfriendly
API. IntelliSense isn't going to be of much help here, because when you want to create
an instance of OrderProcessor, it's not going to remind you that you need to statically
configure OrderShipperFactory first. Enter lots of run-time exceptions.
</p>
        <p>
Another issue is that he allows a <em>concrete</em> implementation of an interface
to <em>change the design</em> of the OrderProcessor class - that's hardly in the spirit
of the Liskov Substitution Principle. I consider this a strong design smell.
</p>
        <p>
One of the commenters (Alwin) suggests instead injecting an IOrderShipperFactory.
While this is a better option, it still suffers from letting a concrete implementation
influence the design, but there's a better solution.
</p>
        <p>
First of all we should realize that the whole case is a bit construed because although
the IOrderShipper implementation may be expensive to create, there's no need to create
a new instance for every OrderProcessor. Instead, we can use the so-called Singleton
lifetime style where we <em>share or reuse</em> a single IOrderShipper instance between
multiple OrderProcessor instances.
</p>
        <p>
The beauty of this is that we can wait making that decision until we wire up the actual
dependencies. If we have implementations of IOrderShipper that are inexpensive to
create, we may still decide to create a new instance every time.
</p>
        <p>
There may still be a corner case where a shared instance doesn't work for a particular
implementation (perhaps because it's not thread-safe). In such cases, we can use Lazy
loading to create a LazyOrderShipper like this (for clarity I've omitted making this
implementation thread-safe, but that would be trivial to do):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LazyOrderShipper\cf0  : \cf4 IOrderShipper\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf4 OrderShipper\cf0  shipper;\par ??\par ??\cf1     #region\cf0  IOrderShipper Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Ship(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf1 if\cf0  (\cf1 this\cf0 .shipper == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 this\cf0 .shipper = \cf1 new\cf0  \cf4 OrderShipper\cf0 ();\par ??        \}\par ??        \cf1 this\cf0 .shipper.Ship(order);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">LazyOrderShipper</span> : <span style="color: #2b91af">IOrderShipper</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: #2b91af">OrderShipper</span> shipper;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IOrderShipper Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Ship(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (<span style="color: blue">this</span>.shipper
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.shipper
= <span style="color: blue">new</span><span style="color: #2b91af">OrderShipper</span>();</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice that this implementation of IOrderShipper only creates the expensive OrderShipper
instance when it needs it.
</p>
        <p>
Instead of directly injecting the expensive OrderShipper instance directly into OrderProcessor,
we wrap it in the LazyOrderShipper class and inject that instead. The following test
proves the point:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ProcessWhenUsingLazyOrderShipperIsFastWhenValidatorDoesNotValidateOrder()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  stopwatch = \cf4 new\cf0  \cf3 Stopwatch\cf0 ();\par ??    stopwatch.Start();\par ??\par ??    \cf4 var\cf0  order = \cf4 new\cf0  \cf3 Order\cf0 ();\par ??\par ??    \cf4 var\cf0  validator = \cf4 new\cf0  \cf3 Mock\cf0 &lt;\cf3 IOrderValidator\cf0 &gt;();\par ??    validator.Setup(v =&gt; \par ??        v.Validate(order)).Returns(\cf4 false\cf0 );\par ??\par ??    \cf4 var\cf0  shipper = \cf4 new\cf0  \cf3 LazyOrderShipper\cf0 ();\par ??\par ??    \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 OrderProcessor\cf0 (validator.Object,\par ??        shipper);\par ??    \cf5 // Exercise system\par ??\cf0     sut.Process(order);\par ??    \cf5 // Verify outcome\par ??\cf0     stopwatch.Stop();\par ??    \cf3 Assert\cf0 .IsTrue(stopwatch.Elapsed &lt; \par ??        \cf3 TimeSpan\cf0 .FromMilliseconds(777));\par ??    \cf3 Console\cf0 .WriteLine(stopwatch.Elapsed);\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> OrderProcessorIsFast()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> stopwatch
= <span style="color: blue">new</span><span style="color: #2b91af">Stopwatch</span>();</pre>
          <pre style="margin: 0px">    stopwatch.Start();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> order
= <span style="color: blue">new</span><span style="color: #2b91af">Order</span>();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> validator
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">    validator.Setup(v =&gt; </pre>
          <pre style="margin: 0px">        v.Validate(order)).Returns(<span style="color: blue">false</span>);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> shipper
= <span style="color: blue">new</span><span style="color: #2b91af">LazyOrderShipper</span>();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">OrderProcessor</span>(validator.Object,</pre>
          <pre style="margin: 0px">        shipper);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.Process(order);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    stopwatch.Stop();</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.IsTrue(stopwatch.Elapsed
&lt; </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">TimeSpan</span>.FromMilliseconds(777));</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Console</span>.WriteLine(stopwatch.Elapsed);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This test is <em>significantly faster</em> than 777 milliseconds because the OrderShipper
never comes into play. In fact, the stopwatch instance reports that the elapsed time
was around 3 ms!
</p>
        <p>
The bottom line is that Constructor Injection is <em>not</em> an anti-pattern. On
the contrary, it is the <em>most powerful DI pattern</em> available, and you should
think twice before deviating from it.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=844f19d3-5b3b-4b1b-b9c9-f53059a5079f" />
      </body>
      <title>Rebuttal: Constructor over-injection anti-pattern</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,844f19d3-5b3b-4b1b-b9c9-f53059a5079f.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx</link>
      <pubDate>Wed, 20 Jan 2010 16:28:03 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://jeffreypalermo.com/"&gt;Jeffrey Palermo&lt;/a&gt; recently posted a blog post
titled &lt;a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/"&gt;Constructor
over-injection anti-pattern&lt;/a&gt; – go read his post first if you want to be able to
follow my arguments.
&lt;/p&gt;
&lt;p&gt;
His point seems to be that Constructor Injection can be an anti-pattern if applied
too much, particularly if a consumer doesn't need a particular dependency in the majority
of cases.
&lt;/p&gt;
&lt;p&gt;
The problem is illustrated in this little code snippet:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 bool\cf0  isValid = _validator.Validate(order);  \par ??\cf1 if\cf0  (isValid) \par ??\{\par ??    _shipper.Ship(order);  \par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;bool&lt;/span&gt; isValid
= _validator.Validate(order);&amp;nbsp; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;if&lt;/span&gt; (isValid) &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; _shipper.Ship(order);&amp;nbsp; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
If the Validate method returns false often, the shipper dependency is never needed. 
&lt;/p&gt;
&lt;p&gt;
This, he argues, can lead to inefficiencies if the dependency is costly to create.
It's not a good thing to require a costly dependency if you are not going to use it
in a lot of cases.
&lt;/p&gt;
&lt;p&gt;
That sounds like a reasonable statement, but is it really? And is the proposed solution
a good solution?
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;No, this isn't a reasonable statement, and the proposed solution isn't a good
solution.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
It would seem like there's a problem with Constructor Injection, but in reality the
problem is that it is being used incorrectly and in too constrained a way.
&lt;/p&gt;
&lt;p&gt;
The proposed solution is problematic because it involves tightly coupling the code
to OrderShipperFactory. This is more or less a specialized application of the Service
Locator anti-pattern.
&lt;/p&gt;
&lt;p&gt;
Consumers of OrderProcessor have no static type information to warn them that they
need to configure the OrderShipperFactory.CreationClosure static member - a completely
unrelated type. This may technically work, but creates a very developer-unfriendly
API. IntelliSense isn't going to be of much help here, because when you want to create
an instance of OrderProcessor, it's not going to remind you that you need to statically
configure OrderShipperFactory first. Enter lots of run-time exceptions.
&lt;/p&gt;
&lt;p&gt;
Another issue is that he allows a &lt;em&gt;concrete&lt;/em&gt; implementation of an interface
to &lt;em&gt;change the design&lt;/em&gt; of the OrderProcessor class - that's hardly in the spirit
of the Liskov Substitution Principle. I consider this a strong design smell.
&lt;/p&gt;
&lt;p&gt;
One of the commenters (Alwin) suggests instead injecting an IOrderShipperFactory.
While this is a better option, it still suffers from letting a concrete implementation
influence the design, but there's a better solution.
&lt;/p&gt;
&lt;p&gt;
First of all we should realize that the whole case is a bit construed because although
the IOrderShipper implementation may be expensive to create, there's no need to create
a new instance for every OrderProcessor. Instead, we can use the so-called Singleton
lifetime style where we &lt;em&gt;share or reuse&lt;/em&gt; a single IOrderShipper instance between
multiple OrderProcessor instances.
&lt;/p&gt;
&lt;p&gt;
The beauty of this is that we can wait making that decision until we wire up the actual
dependencies. If we have implementations of IOrderShipper that are inexpensive to
create, we may still decide to create a new instance every time.
&lt;/p&gt;
&lt;p&gt;
There may still be a corner case where a shared instance doesn't work for a particular
implementation (perhaps because it's not thread-safe). In such cases, we can use Lazy
loading to create a LazyOrderShipper like this (for clarity I've omitted making this
implementation thread-safe, but that would be trivial to do):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LazyOrderShipper\cf0  : \cf4 IOrderShipper\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf4 OrderShipper\cf0  shipper;\par ??\par ??\cf1     #region\cf0  IOrderShipper Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Ship(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf1 if\cf0  (\cf1 this\cf0 .shipper == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 this\cf0 .shipper = \cf1 new\cf0  \cf4 OrderShipper\cf0 ();\par ??        \}\par ??        \cf1 this\cf0 .shipper.Ship(order);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LazyOrderShipper&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderShipper&lt;/span&gt; shipper;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IOrderShipper Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Ship(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (&lt;span style="color: blue"&gt;this&lt;/span&gt;.shipper
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.shipper
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderShipper&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that this implementation of IOrderShipper only creates the expensive OrderShipper
instance when it needs it.
&lt;/p&gt;
&lt;p&gt;
Instead of directly injecting the expensive OrderShipper instance directly into OrderProcessor,
we wrap it in the LazyOrderShipper class and inject that instead. The following test
proves the point:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ProcessWhenUsingLazyOrderShipperIsFastWhenValidatorDoesNotValidateOrder()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  stopwatch = \cf4 new\cf0  \cf3 Stopwatch\cf0 ();\par ??    stopwatch.Start();\par ??\par ??    \cf4 var\cf0  order = \cf4 new\cf0  \cf3 Order\cf0 ();\par ??\par ??    \cf4 var\cf0  validator = \cf4 new\cf0  \cf3 Mock\cf0 &amp;lt;\cf3 IOrderValidator\cf0 &amp;gt;();\par ??    validator.Setup(v =&amp;gt; \par ??        v.Validate(order)).Returns(\cf4 false\cf0 );\par ??\par ??    \cf4 var\cf0  shipper = \cf4 new\cf0  \cf3 LazyOrderShipper\cf0 ();\par ??\par ??    \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 OrderProcessor\cf0 (validator.Object,\par ??        shipper);\par ??    \cf5 // Exercise system\par ??\cf0     sut.Process(order);\par ??    \cf5 // Verify outcome\par ??\cf0     stopwatch.Stop();\par ??    \cf3 Assert\cf0 .IsTrue(stopwatch.Elapsed &amp;lt; \par ??        \cf3 TimeSpan\cf0 .FromMilliseconds(777));\par ??    \cf3 Console\cf0 .WriteLine(stopwatch.Elapsed);\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; OrderProcessorIsFast()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; stopwatch
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Stopwatch&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; stopwatch.Start();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; order
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; validator.Setup(v =&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; v.Validate(order)).Returns(&lt;span style="color: blue"&gt;false&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LazyOrderShipper&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt;(validator.Object,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.Process(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; stopwatch.Stop();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(stopwatch.Elapsed
&amp;lt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;.FromMilliseconds(777));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Console&lt;/span&gt;.WriteLine(stopwatch.Elapsed);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This test is &lt;em&gt;significantly faster&lt;/em&gt; than 777 milliseconds because the OrderShipper
never comes into play. In fact, the stopwatch instance reports that the elapsed time
was around 3 ms!
&lt;/p&gt;
&lt;p&gt;
The bottom line is that Constructor Injection is &lt;em&gt;not&lt;/em&gt; an anti-pattern. On
the contrary, it is the &lt;em&gt;most powerful DI pattern&lt;/em&gt; available, and you should
think twice before deviating from it.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=844f19d3-5b3b-4b1b-b9c9-f53059a5079f" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,844f19d3-5b3b-4b1b-b9c9-f53059a5079f.aspx</comments>
      <category>Dependency Injection</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=9d21d46b-ecde-4d81-bfbb-71f1a6e342a7</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,9d21d46b-ecde-4d81-bfbb-71f1a6e342a7.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,9d21d46b-ecde-4d81-bfbb-71f1a6e342a7.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=9d21d46b-ecde-4d81-bfbb-71f1a6e342a7</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> 1.0 Release Candidate 1
is now available on the CodePlex site! AutoFixture is now almost ten months old and
has seen extensive use internally in <a href="http://www.safewhere.net/">Safewhere</a> during
most of this time. It has proven to be very stable, expressive and generally a delight
to use.
</p>
        <p>
If all goes well, the Release Candidate period will be short. Key users have a chance
to veto the this version, but if no-one complains within a week from now, we will
promote RC1 to version 1.0.
</p>
        <p>
The <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=38665">RC1
release page</a> has more detail about this particular release.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9d21d46b-ecde-4d81-bfbb-71f1a6e342a7" />
      </body>
      <title>AutoFixture 1.0 RC1</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,9d21d46b-ecde-4d81-bfbb-71f1a6e342a7.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/13/AutoFixture10RC1.aspx</link>
      <pubDate>Wed, 13 Jan 2010 22:48:13 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 1.0 Release Candidate 1
is now available on the CodePlex site! AutoFixture is now almost ten months old and
has seen extensive use internally in &lt;a href="http://www.safewhere.net/"&gt;Safewhere&lt;/a&gt; during
most of this time. It has proven to be very stable, expressive and generally a delight
to use.
&lt;/p&gt;
&lt;p&gt;
If all goes well, the Release Candidate period will be short. Key users have a chance
to veto the this version, but if no-one complains within a week from now, we will
promote RC1 to version 1.0.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=38665"&gt;RC1
release page&lt;/a&gt; has more detail about this particular release.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9d21d46b-ecde-4d81-bfbb-71f1a6e342a7" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,9d21d46b-ecde-4d81-bfbb-71f1a6e342a7.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=b4ca21d4-9046-4cff-bb74-3d0a50c958de</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=b4ca21d4-9046-4cff-bb74-3d0a50c958de</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a <a href="http://blog.ploeh.dk/2009/11/26/AnonymousDo.aspx">previous post</a> I
described how <a href="http://autofixture.codeplex.com/">AutoFixture</a>'s Do method
can let you invoke commands on your <a href="http://xunitpatterns.com/SUT.html">SUT</a> with <a href="http://xunitpatterns.com/Dummy%20Object.html">Dummy</a> values
for the parameters you don't care about.
</p>
        <p>
The Get method is the equivalent method you can use when the member you are invoking
returns a value. In other words: if you want to call a method on your SUT to get a
value, but you don't want the hassle of coming up with values you don't care about,
you can let the Get method supply those values for you.
</p>
        <p>
In today's example I will demonstrate a unit test that verifies the behavior of a
custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't
really matter. The point is that a ModelBinder must implement the <a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imodelbinder.aspx">IModelBinder</a> interface
that defines a single method:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">object</span> BindModel(<span style="color: #2b91af">ControllerContext</span> controllerContext,
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">ModelBindingContext</span> bindingContext);
</p>
        </div>
        <p>
In many cases we don't care about one or the other of these parameters, but we still
need to supply them when unit testing.
</p>
        <p>
The example is a bit more complex than some of my other sample code, but once in a
while I like to provide you with slightly more realistic AutoFixture examples. Still,
it's only 10 lines of code, but it looks like a lot more because I have wrapped several
of the lines so that the code is still readable on small screens.
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
[<span style="color: #2b91af">TestMethod</span>]
</p>
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> BindModelWillReturnCorrectResult()
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: green">// Fixture setup</span></p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> fixture = <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();
</p>
          <p style="margin: 0px">
    fixture.Customize&lt;<span style="color: #2b91af">ControllerContext</span>&gt;(ob
=&gt;
</p>
          <p style="margin: 0px">
        ob.OmitAutoProperties());
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> value = fixture.CreateAnonymous(<span style="color: #a31515">"Value"</span>);
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> bindingContext = <span style="color: blue">new</span><span style="color: #2b91af">ModelBindingContext</span>();
</p>
          <p style="margin: 0px">
    bindingContext.ValueProvider = 
</p>
          <p style="margin: 0px">
        <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: blue">string</span>, <span style="color: #2b91af">ValueProviderResult</span>&gt;();
</p>
          <p style="margin: 0px">
    bindingContext.ValueProvider[<span style="color: #a31515">"MyValue"</span>]
= 
</p>
          <p style="margin: 0px">
        <span style="color: blue">new</span><span style="color: #2b91af">ValueProviderResult</span>(value,
value, 
</p>
          <p style="margin: 0px">
            <span style="color: #2b91af">CultureInfo</span>.CurrentCulture);
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> expectedResult = 
</p>
          <p style="margin: 0px">
        <span style="color: blue">new</span><span style="color: blue">string</span>(value.Reverse().ToArray());
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> sut = fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyModelBinder</span>&gt;();
</p>
          <p style="margin: 0px">
    <span style="color: green">// Exercise system</span></p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> result = fixture.Get((<span style="color: #2b91af">ControllerContext</span> cc)
=&gt;
</p>
          <p style="margin: 0px">
        sut.BindModel(cc, bindingContext));
</p>
          <p style="margin: 0px">
    <span style="color: green">// Verify outcome</span></p>
          <p style="margin: 0px">
    <span style="color: #2b91af">Assert</span>.AreEqual(expectedResult,
result, <span style="color: #a31515">"BindModel"</span>);
</p>
          <p style="margin: 0px">
    <span style="color: green">// Teardown</span></p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
The first part simply creates the Fixture object and <a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx">customizes</a> it
to <a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx">disable
AutoProperties</a> for all ControllerContext instances (otherwise we would have to
set up a lot of <a href="http://xunitpatterns.com/Test%20Double.html">Test Doubles</a> for
such properties as HttpContext, RequestContext etc.).
</p>
        <p>
The next part of the test sets up a ModelBindingContext instance that will be used
to exercise the SUT. In this test case, the <em>bindingContext</em> parameter of the
BindModel method is important, so I explicitly set that up. On the other hand, I don't
care about the <em>controllerContext</em> parameter in this test case, so I ask the
Get method to take care of that for me:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">var</span> result = fixture.Get((<span style="color: #2b91af">ControllerContext</span> cc)
=&gt;
</p>
          <p style="margin: 0px">
    sut.BindModel(cc, bindingContext));
</p>
        </div>
        <p>
The Get method creates a Dummy value for the ControllerContext, whereas I can still
use the outer variable <em>bindingContext</em> to call the BindModel method. The return
value of the BindModel method is returned to the <em>result</em> variable by the Get
method.
</p>
        <p>
Like the Do methods, the Get methods are generic methods. The one invoked in this
example has this signature:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span> TResult Get&lt;T, TResult&gt;(<span style="color: #2b91af">Func</span>&lt;T,
TResult&gt; function);
</p>
        </div>
        <p>
There are also overloads that works with the versions of the Func delegate that takes
two, three and four parameters.
</p>
        <p>
As the Do methods, the Get methods are convenience methods that let you concentrate
on writing the test code you care about while it takes care of all the rest. You could
have written a slightly more complex version that didn't use Get but instead used
the CreateAnonymous method to create an Anonymous Variable for the ControllerContext,
but this way is slightly more succinct.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b4ca21d4-9046-4cff-bb74-3d0a50c958de" />
      </body>
      <title>Anonymous Get</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/04/AnonymousGet.aspx</link>
      <pubDate>Mon, 04 Jan 2010 20:53:24 GMT</pubDate>
      <description>&lt;p&gt;
In a &lt;a href="http://blog.ploeh.dk/2009/11/26/AnonymousDo.aspx"&gt;previous post&lt;/a&gt; I
described how &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;'s Do method
can let you invoke commands on your &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt; with &lt;a href="http://xunitpatterns.com/Dummy%20Object.html"&gt;Dummy&lt;/a&gt; values
for the parameters you don't care about.
&lt;/p&gt;
&lt;p&gt;
The Get method is the equivalent method you can use when the member you are invoking
returns a value. In other words: if you want to call a method on your SUT to get a
value, but you don't want the hassle of coming up with values you don't care about,
you can let the Get method supply those values for you.
&lt;/p&gt;
&lt;p&gt;
In today's example I will demonstrate a unit test that verifies the behavior of a
custom ASP.NET MVC ModelBinder. If you don't know anything about ASP.NET MVC it doesn't
really matter. The point is that a ModelBinder must implement the &lt;a href="http://msdn.microsoft.com/en-us/library/system.web.mvc.imodelbinder.aspx"&gt;IModelBinder&lt;/a&gt; interface
that defines a single method:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;object&lt;/span&gt; BindModel(&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; controllerContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ModelBindingContext&lt;/span&gt; bindingContext);
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
In many cases we don't care about one or the other of these parameters, but we still
need to supply them when unit testing.
&lt;/p&gt;
&lt;p&gt;
The example is a bit more complex than some of my other sample code, but once in a
while I like to provide you with slightly more realistic AutoFixture examples. Still,
it's only 10 lines of code, but it looks like a lot more because I have wrapped several
of the lines so that the code is still readable on small screens.
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; BindModelWillReturnCorrectResult()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Fixture setup&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fixture = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Customize&amp;lt;&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt;&amp;gt;(ob
=&amp;gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ob.OmitAutoProperties());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; value = fixture.CreateAnonymous(&lt;span style="color: #a31515"&gt;"Value"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; bindingContext = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ModelBindingContext&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; bindingContext.ValueProvider = 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;ValueProviderResult&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; bindingContext.ValueProvider[&lt;span style="color: #a31515"&gt;"MyValue"&lt;/span&gt;]
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ValueProviderResult&lt;/span&gt;(value,
value, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;CultureInfo&lt;/span&gt;.CurrentCulture);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; expectedResult = 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt;(value.Reverse().ToArray());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut = fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyModelBinder&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Exercise system&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; result = fixture.Get((&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; cc)
=&amp;gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.BindModel(cc, bindingContext));
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Verify outcome&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(expectedResult,
result, &lt;span style="color: #a31515"&gt;"BindModel"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Teardown&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
The first part simply creates the Fixture object and &lt;a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx"&gt;customizes&lt;/a&gt; it
to &lt;a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx"&gt;disable
AutoProperties&lt;/a&gt; for all ControllerContext instances (otherwise we would have to
set up a lot of &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test Doubles&lt;/a&gt; for
such properties as HttpContext, RequestContext etc.).
&lt;/p&gt;
&lt;p&gt;
The next part of the test sets up a ModelBindingContext instance that will be used
to exercise the SUT. In this test case, the &lt;em&gt;bindingContext&lt;/em&gt; parameter of the
BindModel method is important, so I explicitly set that up. On the other hand, I don't
care about the &lt;em&gt;controllerContext&lt;/em&gt; parameter in this test case, so I ask the
Get method to take care of that for me:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;var&lt;/span&gt; result = fixture.Get((&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; cc)
=&amp;gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.BindModel(cc, bindingContext));
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
The Get method creates a Dummy value for the ControllerContext, whereas I can still
use the outer variable &lt;em&gt;bindingContext&lt;/em&gt; to call the BindModel method. The return
value of the BindModel method is returned to the &lt;em&gt;result&lt;/em&gt; variable by the Get
method.
&lt;/p&gt;
&lt;p&gt;
Like the Do methods, the Get methods are generic methods. The one invoked in this
example has this signature:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; TResult Get&amp;lt;T, TResult&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,
TResult&amp;gt; function);
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
There are also overloads that works with the versions of the Func delegate that takes
two, three and four parameters.
&lt;/p&gt;
&lt;p&gt;
As the Do methods, the Get methods are convenience methods that let you concentrate
on writing the test code you care about while it takes care of all the rest. You could
have written a slightly more complex version that didn't use Get but instead used
the CreateAnonymous method to create an Anonymous Variable for the ControllerContext,
but this way is slightly more succinct.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b4ca21d4-9046-4cff-bb74-3d0a50c958de" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,b4ca21d4-9046-4cff-bb74-3d0a50c958de.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=8a17892b-9977-4899-82f7-277a105d156d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=8a17892b-9977-4899-82f7-277a105d156d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I'll be doing a TechTalk on the Managed Extensibility Framework and Dependency Injection
at Microsoft Denmark January 20th 2010.
</p>
        <p>
The talk will be in Danish. <a href="http://msdn.microsoft.com/da-dk/dd796175.aspx">Details
and sign-up here</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=8a17892b-9977-4899-82f7-277a105d156d" />
      </body>
      <title>MEF TechTalk with me</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/20/MEFTechTalkWithMe.aspx</link>
      <pubDate>Sun, 20 Dec 2009 19:56:33 GMT</pubDate>
      <description>&lt;p&gt;
I'll be doing a TechTalk on the Managed Extensibility Framework and Dependency Injection
at Microsoft Denmark January 20th 2010.
&lt;/p&gt;
&lt;p&gt;
The talk will be in Danish. &lt;a href="http://msdn.microsoft.com/da-dk/dd796175.aspx"&gt;Details
and sign-up here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=8a17892b-9977-4899-82f7-277a105d156d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</comments>
      <category>Dependency Injection</category>
      <category>Miscellaneous</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=ee8935b9-d418-4078-99e6-71eec380680b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ee8935b9-d418-4078-99e6-71eec380680b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my previous posts I discussed <a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx">how
to enable global error handling in ASP.NET MVC</a> and <a href="http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx">how
to inject a logging interface into the error handler</a>. In these posts, I simplified
things a bit to get my points across.
</p>
        <p>
In production we don't use a custom ErrorHandlingControllerFactory to configure all
Controllers with error handling, nor do we instantiate IExceptionFilters manually.
What I described was the Poor Man's Dependency Injection (DI) approach, which I find
most appropriate when describing DI concepts.
</p>
        <p>
However, we really use <a href="http://castleproject.org/container/index.html">Castle
Windsor</a> currently, so the wiring looks a bit different although it's still exactly
the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter
are any different than I have already described, but for completeness I wanted to
share a bit of our Windsor code.
</p>
        <p>
This is how we really wire our Controllers:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 container.Register(\cf3 AllTypes\par ??\cf0     .FromAssemblyContaining(representativeControllerType)\par ??    .BasedOn&lt;\cf3 Controller\cf0 &gt;()\par ??    .ConfigureFor&lt;\cf3 Controller\cf0 &gt;(reg =&gt; \par ??        reg.LifeStyle.PerWebRequest.ServiceOverrides(\par ??            \cf4 new\cf0  \{ ActionInvoker = \cf4 typeof\cf0 (\par ??                \cf3 ErrorHandlingControllerActionInvoker\cf0 )\par ??                .FullName \})));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">AllTypes</span></pre>
          <pre style="margin: 0px">    .FromAssemblyContaining(representativeControllerType)</pre>
          <pre style="margin: 0px">    .BasedOn&lt;<span style="color: #2b91af">Controller</span>&gt;()</pre>
          <pre style="margin: 0px">    .ConfigureFor&lt;<span style="color: #2b91af">Controller</span>&gt;(reg
=&gt; </pre>
          <pre style="margin: 0px">        reg.LifeStyle.PerWebRequest.ServiceOverrides(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span> {
ActionInvoker = <span style="color: blue">typeof</span>(</pre>
          <pre style="margin: 0px">                <span style="color: #2b91af">ErrorHandlingControllerActionInvoker</span>)</pre>
          <pre style="margin: 0px">                .FullName })));</pre>
        </div>
        <p>
Most of this statement simply instructs Windsor to scan all types in the specified
assembly for Controller implementations and register them. The interesting part is
the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining
that the ActionInvoker property should be wired up with an instance of the component
registered as ErrorHandlingControllerActionInvoker.
</p>
        <p>
Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance
we need to configure at least one of these as well. Instead of one, however, we have
two:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 container.Register(\cf3 Component\cf0 .For&lt;\cf3 IExceptionFilter\cf0 &gt;()\par ??    .ImplementedBy&lt;\cf3 LoggingExceptionFilter\cf0 &gt;());\par ??container.Register(\cf3 Component\cf0 .For&lt;\cf3 IExceptionFilter\cf0 &gt;()\par ??    .ImplementedBy&lt;\cf3 HandleErrorAttribute\cf0 &gt;());}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IExceptionFilter</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">LoggingExceptionFilter</span>&gt;());</pre>
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IExceptionFilter</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">HandleErrorAttribute</span>&gt;());</pre>
        </div>
        <p>
This is Windsor's elegant way of registering <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorators</a>:
you simply register the Decorator before the decorated type, and it'll Auto-Wire everything
for you.
</p>
        <p>
Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from
the <a href="http://www.codeplex.com/MVCContrib">MVC Contrib</a> project.
</p>
        <p>
To reiterate: You don't have to use Castle Windsor to enable global error handling
or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous
posts, or you can use some other DI Container. The purpose of this post was simply
to demonstrate one way to take it to the next level.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ee8935b9-d418-4078-99e6-71eec380680b" />
      </body>
      <title>Wiring ASP.NET MVC Error Handling with Castle Windsor</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/14/WiringASPNETMVCErrorHandlingWithCastleWindsor.aspx</link>
      <pubDate>Mon, 14 Dec 2009 06:59:32 GMT</pubDate>
      <description>&lt;p&gt;
In my previous posts I discussed &lt;a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx"&gt;how
to enable global error handling in ASP.NET MVC&lt;/a&gt; and &lt;a href="http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx"&gt;how
to inject a logging interface into the error handler&lt;/a&gt;. In these posts, I simplified
things a bit to get my points across.
&lt;/p&gt;
&lt;p&gt;
In production we don't use a custom ErrorHandlingControllerFactory to configure all
Controllers with error handling, nor do we instantiate IExceptionFilters manually.
What I described was the Poor Man's Dependency Injection (DI) approach, which I find
most appropriate when describing DI concepts.
&lt;/p&gt;
&lt;p&gt;
However, we really use &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt; currently, so the wiring looks a bit different although it's still exactly
the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter
are any different than I have already described, but for completeness I wanted to
share a bit of our Windsor code.
&lt;/p&gt;
&lt;p&gt;
This is how we really wire our Controllers:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 container.Register(\cf3 AllTypes\par ??\cf0     .FromAssemblyContaining(representativeControllerType)\par ??    .BasedOn&amp;lt;\cf3 Controller\cf0 &amp;gt;()\par ??    .ConfigureFor&amp;lt;\cf3 Controller\cf0 &amp;gt;(reg =&amp;gt; \par ??        reg.LifeStyle.PerWebRequest.ServiceOverrides(\par ??            \cf4 new\cf0  \{ ActionInvoker = \cf4 typeof\cf0 (\par ??                \cf3 ErrorHandlingControllerActionInvoker\cf0 )\par ??                .FullName \})));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;AllTypes&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .FromAssemblyContaining(representativeControllerType)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .BasedOn&amp;lt;&lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ConfigureFor&amp;lt;&lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&amp;gt;(reg
=&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; reg.LifeStyle.PerWebRequest.ServiceOverrides(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; {
ActionInvoker = &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerActionInvoker&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .FullName })));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Most of this statement simply instructs Windsor to scan all types in the specified
assembly for Controller implementations and register them. The interesting part is
the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining
that the ActionInvoker property should be wired up with an instance of the component
registered as ErrorHandlingControllerActionInvoker.
&lt;/p&gt;
&lt;p&gt;
Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance
we need to configure at least one of these as well. Instead of one, however, we have
two:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 container.Register(\cf3 Component\cf0 .For&amp;lt;\cf3 IExceptionFilter\cf0 &amp;gt;()\par ??    .ImplementedBy&amp;lt;\cf3 LoggingExceptionFilter\cf0 &amp;gt;());\par ??container.Register(\cf3 Component\cf0 .For&amp;lt;\cf3 IExceptionFilter\cf0 &amp;gt;()\par ??    .ImplementedBy&amp;lt;\cf3 HandleErrorAttribute\cf0 &amp;gt;());}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;&amp;gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is Windsor's elegant way of registering &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorators&lt;/a&gt;:
you simply register the Decorator before the decorated type, and it'll Auto-Wire everything
for you.
&lt;/p&gt;
&lt;p&gt;
Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from
the &lt;a href="http://www.codeplex.com/MVCContrib"&gt;MVC Contrib&lt;/a&gt; project.
&lt;/p&gt;
&lt;p&gt;
To reiterate: You don't have to use Castle Windsor to enable global error handling
or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous
posts, or you can use some other DI Container. The purpose of this post was simply
to demonstrate one way to take it to the next level.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ee8935b9-d418-4078-99e6-71eec380680b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=be8504e1-b78f-4246-9338-717f7d0529b5</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=be8504e1-b78f-4246-9338-717f7d0529b5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a previous post I described <a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx">how
to enable global error handling in ASP.NET MVC applications</a>. Although I spent
some time talking about the importance of DRY, another major motivation for me was
to enable Dependency Injection (DI) with exception handling so that I could log stack
traces before letting ASP.NET MVC handle the exception.
</p>
        <p>
With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter
implementation. As an example I used HandleErrorAttribute, but obviously that doesn't
log anything. Once again, it would be tempting to derive from HandleErrorAttribute
and override its OnException method, but staying true to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> as well as the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/Closed
Principle</a> I rather prefer a <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LoggingExceptionFilter\cf0  : \cf4 IExceptionFilter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IExceptionFilter\cf0  filter;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 ILogWriter\cf0  logWriter;\par ??\par ??    \cf1 public\cf0  LoggingExceptionFilter(\cf4 IExceptionFilter\cf0  filter,\par ??        \cf4 ILogWriter\cf0  logWriter)\par ??    \{\par ??        \cf1 if\cf0  (filter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "filter"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (logWriter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "logWriter"\cf0 );\par ??        \}        \par ??    \par ??        \cf1 this\cf0 .filter = filter;\par ??        \cf1 this\cf0 .logWriter = logWriter;\par ??    \}\par ??\par ??\cf1     #region\cf0  IExceptionFilter Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  OnException(\cf4 ExceptionContext\cf0  filterContext)\par ??    \{\par ??        \cf1 this\cf0 .logWriter.WriteError(filterContext.Exception);\par ??        \cf1 this\cf0 .filter.OnException(filterContext);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">LoggingExceptionFilter</span> : <span style="color: #2b91af">IExceptionFilter</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IExceptionFilter</span> filter;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">ILogWriter</span> logWriter;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> LoggingExceptionFilter(<span style="color: #2b91af">IExceptionFilter</span> filter,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ILogWriter</span> logWriter)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (filter
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (logWriter
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"logWriter"</span>);</pre>
          <pre style="margin: 0px">        }        </pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.filter
= filter;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.logWriter
= logWriter;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IExceptionFilter Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> OnException(<span style="color: #2b91af">ExceptionContext</span> filterContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.logWriter.WriteError(filterContext.Exception);</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.filter.OnException(filterContext);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The LoggingExceptionFilter shown above is unabridged production code. This is all
it takes to bridge the gap between IExceptionFilter and some ILogWriter interface
(replace with the logging framework of your choice). Notice how it simply logs the
error and then passes on exception handling to the decorated IExceptionFilter.
</p>
        <p>
Currently we use HandleErrorAttribute as the decorated filter so that behavior stays
as expected.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 c.ActionInvoker = \par ??    \cf3 new\cf0  \cf4 ErrorHandlingControllerActionInvoker\cf0 (\par ??        \cf3 new\cf0  \cf4 LoggingExceptionFilter\cf0 (\par ??            \cf3 new\cf0  \cf4 HandleErrorAttribute\cf0 (), logWriter));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">c.ActionInvoker = </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingControllerActionInvoker</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">LoggingExceptionFilter</span>(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">HandleErrorAttribute</span>(),
logWriter));</pre>
        </div>
        <p>
This is not too different from before, except that a LoggingExceptionFilter now decorates
the HandleErrorAttribute instance.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be8504e1-b78f-4246-9338-717f7d0529b5" />
      </body>
      <title>LoggingExceptionFilter</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx</link>
      <pubDate>Mon, 07 Dec 2009 06:20:27 GMT</pubDate>
      <description>&lt;p&gt;
In a previous post I described &lt;a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx"&gt;how
to enable global error handling in ASP.NET MVC applications&lt;/a&gt;. Although I spent
some time talking about the importance of DRY, another major motivation for me was
to enable Dependency Injection (DI) with exception handling so that I could log stack
traces before letting ASP.NET MVC handle the exception.
&lt;/p&gt;
&lt;p&gt;
With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter
implementation. As an example I used HandleErrorAttribute, but obviously that doesn't
log anything. Once again, it would be tempting to derive from HandleErrorAttribute
and override its OnException method, but staying true to the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt; as well as the &lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open/Closed
Principle&lt;/a&gt; I rather prefer a &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorator&lt;/a&gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LoggingExceptionFilter\cf0  : \cf4 IExceptionFilter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IExceptionFilter\cf0  filter;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 ILogWriter\cf0  logWriter;\par ??\par ??    \cf1 public\cf0  LoggingExceptionFilter(\cf4 IExceptionFilter\cf0  filter,\par ??        \cf4 ILogWriter\cf0  logWriter)\par ??    \{\par ??        \cf1 if\cf0  (filter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "filter"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (logWriter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "logWriter"\cf0 );\par ??        \}        \par ??    \par ??        \cf1 this\cf0 .filter = filter;\par ??        \cf1 this\cf0 .logWriter = logWriter;\par ??    \}\par ??\par ??\cf1     #region\cf0  IExceptionFilter Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  OnException(\cf4 ExceptionContext\cf0  filterContext)\par ??    \{\par ??        \cf1 this\cf0 .logWriter.WriteError(filterContext.Exception);\par ??        \cf1 this\cf0 .filter.OnException(filterContext);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ILogWriter&lt;/span&gt; logWriter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; LoggingExceptionFilter(&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ILogWriter&lt;/span&gt; logWriter)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (filter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"filter"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (logWriter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"logWriter"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter
= filter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.logWriter
= logWriter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IExceptionFilter Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; OnException(&lt;span style="color: #2b91af"&gt;ExceptionContext&lt;/span&gt; filterContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.logWriter.WriteError(filterContext.Exception);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter.OnException(filterContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The LoggingExceptionFilter shown above is unabridged production code. This is all
it takes to bridge the gap between IExceptionFilter and some ILogWriter interface
(replace with the logging framework of your choice). Notice how it simply logs the
error and then passes on exception handling to the decorated IExceptionFilter.
&lt;/p&gt;
&lt;p&gt;
Currently we use HandleErrorAttribute as the decorated filter so that behavior stays
as expected.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 c.ActionInvoker = \par ??    \cf3 new\cf0  \cf4 ErrorHandlingControllerActionInvoker\cf0 (\par ??        \cf3 new\cf0  \cf4 LoggingExceptionFilter\cf0 (\par ??            \cf3 new\cf0  \cf4 HandleErrorAttribute\cf0 (), logWriter));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;c.ActionInvoker = &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerActionInvoker&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;(),
logWriter));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is not too different from before, except that a LoggingExceptionFilter now decorates
the HandleErrorAttribute instance.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be8504e1-b78f-4246-9338-717f7d0529b5" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=08e6da72-55c6-4059-a7c2-8b4b32779ee3</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,08e6da72-55c6-4059-a7c2-8b4b32779ee3.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,08e6da72-55c6-4059-a7c2-8b4b32779ee3.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=08e6da72-55c6-4059-a7c2-8b4b32779ee3</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A reader <a href="http://blog.ploeh.dk/CommentView,guid,292e8e24-b3ae-4805-94c0-9511f23a6ec4.aspx#commentstart">asked
me</a> how <a href="http://autofixture.codeplex.com/">AutoFixture</a> can deal with
arrays as fields on a class. More specifically, given a class like MyClassA, how can
AutoFixture assign a proper array with initialized values to Items?
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 MyClassA\par ??\cf0 \{\par ??    \cf1 public\cf0  \cf4 MyClassB\cf0 [] Items;\par ??    \cf1 public\cf0  \cf4 MyClassC\cf0  C;\par ??    \cf1 public\cf0  \cf4 MyClassD\cf0  D;\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">MyClassA</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">MyClassB</span>[]
Items;</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">MyClassC</span> C;</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">MyClassD</span> D;</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Ignoring the bad practice of publicly exposing fields, the main problem is that AutoFixture
has no inherent understanding of arrays, so if we try to create a new instance of
MyClassA by invoking the <a href="http://blog.ploeh.dk/2009/03/24/HowAutoFixtureCreatesObjects.aspx">CreateAnonymous</a> method,
we would end up with Items being an array of nulls.
</p>
        <p>
Obviously we want a populated array instead. There are at least a couple of ways to
reach this goal.
</p>
        <p>
The simplest is just to create it and modify it afterwards:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClassA\cf0 &gt;();\par ??mc.Items = fixture.CreateMany&lt;\cf4 MyClassB\cf0 &gt;().ToArray();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClassA</span>&gt;();</pre>
          <pre style="margin: 0px">mc.Items = fixture.CreateMany&lt;<span style="color: #2b91af">MyClassB</span>&gt;().ToArray();</pre>
        </div>
        <p>
Although the CreateAnomymous method will assign an unitialized array, we immediately
overwrite the value with an initialized array. The <a href="http://blog.ploeh.dk/2009/05/11/AnonymousSequencesWithAutoFixture.aspx">CreateMany</a> method
returns an IEnumerable&lt;MyClassB&gt; on which we can use the ToArray extension method
to create an array.
</p>
        <p>
The next option is to do almost the same thing, but as a single operation:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.Build&lt;\cf4 MyClassA\cf0 &gt;()\par ??    .With(x =&gt; x.Items, \par ??        fixture.CreateMany&lt;\cf4 MyClassB\cf0 &gt;().ToArray())\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.Build&lt;<span style="color: #2b91af">MyClassA</span>&gt;()</pre>
          <pre style="margin: 0px">    .With(x =&gt; x.Items, </pre>
          <pre style="margin: 0px">        fixture.CreateMany&lt;<span style="color: #2b91af">MyClassB</span>&gt;().ToArray())</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
Besides the different syntax and the lower semicolon count, the biggest difference
is that in this case the Items field is never assigned an unitialized array because <a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx">the
With method ensures that the specified value is assigned immediately</a>.
</p>
        <p>
If you get tired of writing this Builder sequence every time you want to create a
new MyClassA instance, you can <a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx">Customize
the Fixture</a>:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 fixture.Customize&lt;\cf3 MyClassA\cf0 &gt;(ob =&gt;\par ??    ob.With(x =&gt; x.Items, \par ??        fixture.CreateMany&lt;\cf3 MyClassB\cf0 &gt;().ToArray()));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">fixture.Customize&lt;<span style="color: #2b91af">MyClassA</span>&gt;(ob
=&gt;</pre>
          <pre style="margin: 0px">    ob.With(x =&gt; x.Items, </pre>
          <pre style="margin: 0px">        fixture.CreateMany&lt;<span style="color: #2b91af">MyClassB</span>&gt;().ToArray()));</pre>
        </div>
        <p>
With this customization, every time we invoke
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClassA\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClassA</span>&gt;();</pre>
        </div>
        <p>
we will get an instance of MyClassA with a properly initialized Items array.
</p>
        <p>
I hope you find one or more of these methods useful.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=08e6da72-55c6-4059-a7c2-8b4b32779ee3" />
      </body>
      <title>Building and assigning arrays with AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,08e6da72-55c6-4059-a7c2-8b4b32779ee3.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/05/BuildingAndAssigningArraysWithAutoFixture.aspx</link>
      <pubDate>Sat, 05 Dec 2009 00:41:45 GMT</pubDate>
      <description>&lt;p&gt;
A reader &lt;a href="http://blog.ploeh.dk/CommentView,guid,292e8e24-b3ae-4805-94c0-9511f23a6ec4.aspx#commentstart"&gt;asked
me&lt;/a&gt; how &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; can deal with
arrays as fields on a class. More specifically, given a class like MyClassA, how can
AutoFixture assign a proper array with initialized values to Items?
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 MyClassA\par ??\cf0 \{\par ??    \cf1 public\cf0  \cf4 MyClassB\cf0 [] Items;\par ??    \cf1 public\cf0  \cf4 MyClassC\cf0  C;\par ??    \cf1 public\cf0  \cf4 MyClassD\cf0  D;\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClassA&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClassB&lt;/span&gt;[]
Items;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClassC&lt;/span&gt; C;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClassD&lt;/span&gt; D;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Ignoring the bad practice of publicly exposing fields, the main problem is that AutoFixture
has no inherent understanding of arrays, so if we try to create a new instance of
MyClassA by invoking the &lt;a href="http://blog.ploeh.dk/2009/03/24/HowAutoFixtureCreatesObjects.aspx"&gt;CreateAnonymous&lt;/a&gt; method,
we would end up with Items being an array of nulls.
&lt;/p&gt;
&lt;p&gt;
Obviously we want a populated array instead. There are at least a couple of ways to
reach this goal.
&lt;/p&gt;
&lt;p&gt;
The simplest is just to create it and modify it afterwards:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClassA\cf0 &amp;gt;();\par ??mc.Items = fixture.CreateMany&amp;lt;\cf4 MyClassB\cf0 &amp;gt;().ToArray();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassA&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mc.Items = fixture.CreateMany&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassB&lt;/span&gt;&amp;gt;().ToArray();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Although the CreateAnomymous method will assign an unitialized array, we immediately
overwrite the value with an initialized array. The &lt;a href="http://blog.ploeh.dk/2009/05/11/AnonymousSequencesWithAutoFixture.aspx"&gt;CreateMany&lt;/a&gt; method
returns an IEnumerable&amp;lt;MyClassB&amp;gt; on which we can use the ToArray extension method
to create an array.
&lt;/p&gt;
&lt;p&gt;
The next option is to do almost the same thing, but as a single operation:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.Build&amp;lt;\cf4 MyClassA\cf0 &amp;gt;()\par ??    .With(x =&amp;gt; x.Items, \par ??        fixture.CreateMany&amp;lt;\cf4 MyClassB\cf0 &amp;gt;().ToArray())\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassA&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(x =&amp;gt; x.Items, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.CreateMany&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassB&lt;/span&gt;&amp;gt;().ToArray())&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Besides the different syntax and the lower semicolon count, the biggest difference
is that in this case the Items field is never assigned an unitialized array because &lt;a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx"&gt;the
With method ensures that the specified value is assigned immediately&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
If you get tired of writing this Builder sequence every time you want to create a
new MyClassA instance, you can &lt;a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx"&gt;Customize
the Fixture&lt;/a&gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 fixture.Customize&amp;lt;\cf3 MyClassA\cf0 &amp;gt;(ob =&amp;gt;\par ??    ob.With(x =&amp;gt; x.Items, \par ??        fixture.CreateMany&amp;lt;\cf3 MyClassB\cf0 &amp;gt;().ToArray()));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;fixture.Customize&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassA&lt;/span&gt;&amp;gt;(ob
=&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; ob.With(x =&amp;gt; x.Items, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.CreateMany&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassB&lt;/span&gt;&amp;gt;().ToArray()));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With this customization, every time we invoke
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClassA\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClassA&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
we will get an instance of MyClassA with a properly initialized Items array.
&lt;/p&gt;
&lt;p&gt;
I hope you find one or more of these methods useful.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=08e6da72-55c6-4059-a7c2-8b4b32779ee3" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,08e6da72-55c6-4059-a7c2-8b4b32779ee3.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=1b080ce4-b5e9-4332-80dc-a362a0cc083d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=1b080ce4-b5e9-4332-80dc-a362a0cc083d</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
ASP.NET MVC comes with an error-handling feature that enables you to show nice error
Views to your users instead of the dreaded Yellow Screen of Death. The most prominently
described technique involves attributing either you Controller or a single Controller
action, like we see in the AccountController created by the Visual Studio project
template.
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
[<span style="color: #2b91af">HandleError</span>]
</p>
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">AccountController</span> : <span style="color: #2b91af">Controller</span> {
}
</p>
        </div>
        <p>
That sure is easy, but I don't like it for a number of reasons:
</p>
        <ul>
          <li>
Even though you can derive from HandleErrorAttribute, it's impossible to inject any
dependencies into Attributes because they must be fully constructed at compile-time.
That makes it really difficult to log errors to an interface. 
</li>
          <li>
It violates the DRY principle. Although it can be applied at the Controller level,
I still must remember to attribute all of my Controllers with the HandleErrorAttribute.</li>
        </ul>
        <p>
Another approach is to override Controller.OnException. That solves the DI problem,
but not the DRY problem.
</p>
        <p>
Attentive readers may now point out that I can define a base Controller that implements
the proper error handling, and require that all my Controllers derive from this base
Controller, but that doesn't satisfy me:
</p>
        <p>
First of all, it still violates the DRY principle. Whether I have to remember to apply
a [HandleError] attribute or derive from a : MyBaseController amounts to the same
thing. I (and all my team members) have to remember this always. It's unnecessary
project friction.
</p>
        <p>
The second thing that bugs me about this approach is that I really do <em>favor composition
over inheritance</em>. Error handling is a <em>cross-cutting concern</em>, so why
should all my Controllers have to derive from a base controller to enable this? That
is absurd.
</p>
        <p>
Fortunately, ASP.NET MVC offers a third way.
</p>
        <p>
The key lies in the Controller base class and how it deals with IExceptionFilters
(which HandleErrorAttribute implements). When a Controller action is invoked, this
actually happens through an IActionInvoker. The default ControllerActionInvoker is
responsible for gathering the list of IExceptionFilters, so the first thing we can
do is to derive from that and override its GetFilters method:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ErrorHandlingActionInvoker</span> :
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">ControllerActionInvoker</span></p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IExceptionFilter</span> filter;
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span> ErrorHandlingActionInvoker(
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">IExceptionFilter</span> filter)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (filter
== <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.filter
= filter;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: #2b91af">FilterInfo</span> GetFilters(
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">ControllerContext</span> controllerContext,
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">ActionDescriptor</span> actionDescriptor)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> filterInfo
= 
</p>
          <p style="margin: 0px">
            <span style="color: blue">base</span>.GetFilters(controllerContext, 
</p>
          <p style="margin: 0px">
            actionDescriptor);
</p>
          <p style="margin: 0px">
        filterInfo.ExceptionFilters.Add(<span style="color: blue">this</span>.filter);
</p>
          <p style="margin: 0px">
        <span style="color: blue">return</span> filterInfo;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not
tightly binding it to any particular implementation – it will work with any IExceptionFilter
we give it, so it simply serves the purpose of adding the filter at the right stage
so that it can deal with otherwise unhandled exceptions. It's pure infrastructure
code.
</p>
        <p>
Notice that I first invoke base.GetFilters and then add the injected filter to the
returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to
attempt to deal with the error first.
</p>
        <p>
This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every
Controller in the application. This can be done using a custom ControllerFactory:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ErrorHandlingControllerFactory</span> : 
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">DefaultControllerFactory</span></p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span><span style="color: blue">override</span><span style="color: #2b91af">IController</span> CreateController(
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">RequestContext</span> requestContext,
</p>
          <p style="margin: 0px">
        <span style="color: blue">string</span> controllerName)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> controller
= 
</p>
          <p style="margin: 0px">
            <span style="color: blue">base</span>.CreateController(requestContext,
</p>
          <p style="margin: 0px">
            controllerName);
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> c
= controller <span style="color: blue">as</span><span style="color: #2b91af">Controller</span>;
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (c
!= <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            c.ActionInvoker
= 
</p>
          <p style="margin: 0px">
                <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingActionInvoker</span>(
</p>
          <p style="margin: 0px">
                    <span style="color: blue">new</span><span style="color: #2b91af">HandleErrorAttribute</span>());
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">return</span> controller;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
Notice that I'm simply deriving from the DefaultControllerFactory and overriding the
CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.
</p>
        <p>
In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker
instance. This seems weird, but it's the HandleErrorAttribute that implements the
default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter,
it works like a charm.
</p>
        <p>
The only thing left to do is to wire up the custom ErrorHandlingControllerFactory
in global.asax like this:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: #2b91af">ControllerBuilder</span>.Current.SetControllerFactory(
</p>
          <p style="margin: 0px">
    <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingControllerFactory</span>());
</p>
        </div>
        <p>
Now any Controller action that throws an exception is gracefully handled by the injected
IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters,
any normal [HandleError] attribute and Controller.OnException override gets a chance
to deal with the exception first, so this doesn't even change behavior of existing
code.
</p>
        <p>
If you are trying this out on your own development machine, remember that you must
modify your web.config like so:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">customErrors</span>
            <span style="color: blue">
            </span>
            <span style="color: red">mode</span>
            <span style="color: blue">=</span>"<span style="color: blue">On</span>"<span style="color: blue"> /&gt;</span></p>
        </div>
        <p>
If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on
your local box.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1b080ce4-b5e9-4332-80dc-a362a0cc083d" />
      </body>
      <title>Global Error Handling in ASP.NET MVC</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx</link>
      <pubDate>Tue, 01 Dec 2009 06:37:01 GMT</pubDate>
      <description>&lt;p&gt;
ASP.NET MVC comes with an error-handling feature that enables you to show nice error
Views to your users instead of the dreaded Yellow Screen of Death. The most prominently
described technique involves attributing either you Controller or a single Controller
action, like we see in the AccountController created by the Visual Studio project
template.
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
[&lt;span style="color: #2b91af"&gt;HandleError&lt;/span&gt;]
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;AccountController&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt; {
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
That sure is easy, but I don't like it for a number of reasons:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
Even though you can derive from HandleErrorAttribute, it's impossible to inject any
dependencies into Attributes because they must be fully constructed at compile-time.
That makes it really difficult to log errors to an interface. 
&lt;li&gt;
It violates the DRY principle. Although it can be applied at the Controller level,
I still must remember to attribute all of my Controllers with the HandleErrorAttribute.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Another approach is to override Controller.OnException. That solves the DI problem,
but not the DRY problem.
&lt;/p&gt;
&lt;p&gt;
Attentive readers may now point out that I can define a base Controller that implements
the proper error handling, and require that all my Controllers derive from this base
Controller, but that doesn't satisfy me:
&lt;/p&gt;
&lt;p&gt;
First of all, it still violates the DRY principle. Whether I have to remember to apply
a [HandleError] attribute or derive from a : MyBaseController amounts to the same
thing. I (and all my team members) have to remember this always. It's unnecessary
project friction.
&lt;/p&gt;
&lt;p&gt;
The second thing that bugs me about this approach is that I really do &lt;em&gt;favor composition
over inheritance&lt;/em&gt;. Error handling is a &lt;em&gt;cross-cutting concern&lt;/em&gt;, so why
should all my Controllers have to derive from a base controller to enable this? That
is absurd.
&lt;/p&gt;
&lt;p&gt;
Fortunately, ASP.NET MVC offers a third way.
&lt;/p&gt;
&lt;p&gt;
The key lies in the Controller base class and how it deals with IExceptionFilters
(which HandleErrorAttribute implements). When a Controller action is invoked, this
actually happens through an IActionInvoker. The default ControllerActionInvoker is
responsible for gathering the list of IExceptionFilters, so the first thing we can
do is to derive from that and override its GetFilters method:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingActionInvoker&lt;/span&gt; :
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ControllerActionInvoker&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; ErrorHandlingActionInvoker(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (filter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"filter"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter
= filter;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;protected&lt;/span&gt; &lt;span style="color: blue"&gt;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FilterInfo&lt;/span&gt; GetFilters(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt; controllerContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ActionDescriptor&lt;/span&gt; actionDescriptor)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; filterInfo
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;base&lt;/span&gt;.GetFilters(controllerContext, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; actionDescriptor);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; filterInfo.ExceptionFilters.Add(&lt;span style="color: blue"&gt;this&lt;/span&gt;.filter);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; filterInfo;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Here I'm simply injecting an IExceptionFilter instance into this class, so I'm not
tightly binding it to any particular implementation – it will work with any IExceptionFilter
we give it, so it simply serves the purpose of adding the filter at the right stage
so that it can deal with otherwise unhandled exceptions. It's pure infrastructure
code.
&lt;/p&gt;
&lt;p&gt;
Notice that I first invoke base.GetFilters and then add the injected filter to the
returned list of filters. This allows the normal ASP.NET MVC IExceptionFilters to
attempt to deal with the error first.
&lt;/p&gt;
&lt;p&gt;
This ErrorHandlingActionInvoker is only valuable if we can assign it to each and every
Controller in the application. This can be done using a custom ControllerFactory:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerFactory&lt;/span&gt; : 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DefaultControllerFactory&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IController&lt;/span&gt; CreateController(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;RequestContext&lt;/span&gt; requestContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;string&lt;/span&gt; controllerName)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; controller
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;base&lt;/span&gt;.CreateController(requestContext,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; controllerName);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; c
= controller &lt;span style="color: blue"&gt;as&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (c
!= &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c.ActionInvoker
= 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingActionInvoker&lt;/span&gt;(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; controller;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that I'm simply deriving from the DefaultControllerFactory and overriding the
CreateController method to assign the ErrorHandlingActionInvoker to the created Controller.
&lt;/p&gt;
&lt;p&gt;
In this example, I have chosen to inject the HandleErrorAttribute into the ErrorHandlingActionInvoker
instance. This seems weird, but it's the HandleErrorAttribute that implements the
default error handling logic in ASP.NET MVC, and since it implements IExceptionFilter,
it works like a charm.
&lt;/p&gt;
&lt;p&gt;
The only thing left to do is to wire up the custom ErrorHandlingControllerFactory
in global.asax like this:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: #2b91af"&gt;ControllerBuilder&lt;/span&gt;.Current.SetControllerFactory(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerFactory&lt;/span&gt;());
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Now any Controller action that throws an exception is gracefully handled by the injected
IExceptionFilter. Since the filter is added as the last in the list of ExceptionFilters,
any normal [HandleError] attribute and Controller.OnException override gets a chance
to deal with the exception first, so this doesn't even change behavior of existing
code.
&lt;/p&gt;
&lt;p&gt;
If you are trying this out on your own development machine, remember that you must
modify your web.config like so:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;customErrors&lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;mode&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;"&lt;span style="color: blue"&gt;On&lt;/span&gt;"&lt;span style="color: blue"&gt; /&amp;gt;&lt;/span&gt;
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
If you run in the RemoteOnly mode, you will still see the Yellow Screen of Death on
your local box.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1b080ce4-b5e9-4332-80dc-a362a0cc083d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,1b080ce4-b5e9-4332-80dc-a362a0cc083d.aspx</comments>
      <category>ASP.NET MVC</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=9da2b80c-55e5-41e9-9940-f660e561204a</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,9da2b80c-55e5-41e9-9940-f660e561204a.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,9da2b80c-55e5-41e9-9940-f660e561204a.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=9da2b80c-55e5-41e9-9940-f660e561204a</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In unit testing an important step is to exercise the <a href="http://xunitpatterns.com/SUT.html">SUT</a>.
The member you want to invoke is often a method that takes one or more parameters,
but in some test cases you don't care about the values of those parameters – you just
want to invoke the method.
</p>
        <p>
You can always make up one or more <a href="http://xunitpatterns.com/Dummy%20Object.html">Dummy</a> parameters
and pass them to the method in question, but you could also use one of <a href="http://autofixture.codeplex.com/">AutoFixture</a>'s
Do convenience methods. There are several overloads that all take delegates that specify
the action in question while providing you with Dummies of any parameters you don't
care about.
</p>
        <p>
A good example is WPF's <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand</a> interface.
The most prevalent method is the Execute method that takes a single <em>parameter</em> parameter:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">void</span> Execute(<span style="color: blue">object</span> parameter);
</p>
        </div>
        <p>
Most of the time we don't really care about the parameter because we only care that
the command was invoked. However, we still need to supply a value for the parameter
when we unit test our ICommand implementations. Obviously, we could just pass in a
new System.Object every time, but why not let AutoFixture take care of that for us?
</p>
        <p>
(You may think that new'ing up a System.Object is something you can easily do yourself,
but imagine other APIs that require much more complex input parameters, and you should
begin to see the potential.)
</p>
        <p>
Here's a state-based unit test that verifies that the Message property of the MyViewModel
class has the correct value after the FooCommand has been invoked:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
[<span style="color: #2b91af">TestMethod</span>]
</p>
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> FooWillUpdateMessage()
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: green">// Fixture setup</span></p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> fixture = <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> sut = fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyViewModel</span>&gt;();
</p>
          <p style="margin: 0px">
    <span style="color: green">// Exercise system</span></p>
          <p style="margin: 0px">
    fixture.Do((<span style="color: blue">object</span> parameter)
=&gt; 
</p>
          <p style="margin: 0px">
        sut.FooCommand.Execute(parameter));
</p>
          <p style="margin: 0px">
    <span style="color: green">// Verify outcome</span></p>
          <p style="margin: 0px">
    <span style="color: #2b91af">Assert</span>.AreEqual(<span style="color: #a31515">"Foo"</span>,
sut.Message, <span style="color: #a31515">"Message"</span>);
</p>
          <p style="margin: 0px">
    <span style="color: green">// Teardown</span></p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
Notice how the Do method takes an Action&lt;object&gt; to specify the method to invoke.
AutoFixture automatically supplies an instance for the <em>parameter</em> parameter
using the same engine to create <a href="http://blogs.msdn.com/ploeh/archive/2008/11/17/anonymous-variables.aspx">Anonymous
variables</a> that it uses for everything else.
</p>
        <p>
The Do method in question is really a generic method with this signature:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> Do&lt;T&gt;(<span style="color: #2b91af">Action</span>&lt;T&gt;
action);
</p>
        </div>
        <p>
There are also overloads that take two, three or four input parameters, corresponding
to the available Action types available in the BCL.
</p>
        <p>
These methods are simply convenience methods that allow you to express your test code
more succinctly than you would otherwise have been able to do.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9da2b80c-55e5-41e9-9940-f660e561204a" />
      </body>
      <title>Anonymous Do</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,9da2b80c-55e5-41e9-9940-f660e561204a.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/26/AnonymousDo.aspx</link>
      <pubDate>Thu, 26 Nov 2009 21:23:46 GMT</pubDate>
      <description>&lt;p&gt;
In unit testing an important step is to exercise the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;.
The member you want to invoke is often a method that takes one or more parameters,
but in some test cases you don't care about the values of those parameters – you just
want to invoke the method.
&lt;/p&gt;
&lt;p&gt;
You can always make up one or more &lt;a href="http://xunitpatterns.com/Dummy%20Object.html"&gt;Dummy&lt;/a&gt; parameters
and pass them to the method in question, but you could also use one of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;'s
Do convenience methods. There are several overloads that all take delegates that specify
the action in question while providing you with Dummies of any parameters you don't
care about.
&lt;/p&gt;
&lt;p&gt;
A good example is WPF's &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx"&gt;ICommand&lt;/a&gt; interface.
The most prevalent method is the Execute method that takes a single &lt;em&gt;parameter&lt;/em&gt; parameter:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;void&lt;/span&gt; Execute(&lt;span style="color: blue"&gt;object&lt;/span&gt; parameter);
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Most of the time we don't really care about the parameter because we only care that
the command was invoked. However, we still need to supply a value for the parameter
when we unit test our ICommand implementations. Obviously, we could just pass in a
new System.Object every time, but why not let AutoFixture take care of that for us?
&lt;/p&gt;
&lt;p&gt;
(You may think that new'ing up a System.Object is something you can easily do yourself,
but imagine other APIs that require much more complex input parameters, and you should
begin to see the potential.)
&lt;/p&gt;
&lt;p&gt;
Here's a state-based unit test that verifies that the Message property of the MyViewModel
class has the correct value after the FooCommand has been invoked:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; FooWillUpdateMessage()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Fixture setup&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fixture = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut = fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Exercise system&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Do((&lt;span style="color: blue"&gt;object&lt;/span&gt; parameter)
=&amp;gt; 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.FooCommand.Execute(parameter));
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Verify outcome&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(&lt;span style="color: #a31515"&gt;"Foo"&lt;/span&gt;,
sut.Message, &lt;span style="color: #a31515"&gt;"Message"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;// Teardown&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
Notice how the Do method takes an Action&amp;lt;object&amp;gt; to specify the method to invoke.
AutoFixture automatically supplies an instance for the &lt;em&gt;parameter&lt;/em&gt; parameter
using the same engine to create &lt;a href="http://blogs.msdn.com/ploeh/archive/2008/11/17/anonymous-variables.aspx"&gt;Anonymous
variables&lt;/a&gt; that it uses for everything else.
&lt;/p&gt;
&lt;p&gt;
The Do method in question is really a generic method with this signature:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Do&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;
action);
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
There are also overloads that take two, three or four input parameters, corresponding
to the available Action types available in the BCL.
&lt;/p&gt;
&lt;p&gt;
These methods are simply convenience methods that allow you to express your test code
more succinctly than you would otherwise have been able to do.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9da2b80c-55e5-41e9-9940-f660e561204a" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,9da2b80c-55e5-41e9-9940-f660e561204a.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
      <category>WPF</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=3bdeeded-974f-4bcd-8042-4928c1459e90</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=3bdeeded-974f-4bcd-8042-4928c1459e90</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://danielfrost.dk/">Daniel Frost</a> has published a podcast where he
discusses Dependency Injection with me. It's about half an hour long and in Danish. <a href="http://danielfrost.dk/post/Frosts-Podcast-Show-7-e28093-Dependency-Injections-med-Mark-Seemann.aspx">Hear
it here</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3bdeeded-974f-4bcd-8042-4928c1459e90" />
      </body>
      <title>Dependency Injection Podcast with me</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/17/DependencyInjectionPodcastWithMe.aspx</link>
      <pubDate>Tue, 17 Nov 2009 18:58:47 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://danielfrost.dk/"&gt;Daniel Frost&lt;/a&gt; has published a podcast where he
discusses Dependency Injection with me. It's about half an hour long and in Danish. &lt;a href="http://danielfrost.dk/post/Frosts-Podcast-Show-7-e28093-Dependency-Injections-med-Mark-Seemann.aspx"&gt;Hear
it here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3bdeeded-974f-4bcd-8042-4928c1459e90" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</comments>
      <category>Dependency Injection</category>
      <category>Miscellaneous</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=4276a194-a567-47ab-80b3-23c2813537f3</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=4276a194-a567-47ab-80b3-23c2813537f3</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When using <a href="http://castleproject.org/container/index.html">Castle Windsor</a> in
web applications you would want to register many of your components with a lifestyle
that is associated with a single request. This is the purpose of the PerWebRequest
lifestyle.
</p>
        <p>
If you try that with ASP.NET MVC on IIS7, you are likely to receive the following
error message:
</p>
        <blockquote>
          <p>
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule 
<br />
Add '&lt;add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" /&gt;' to the &lt;httpModules&gt; section on your web.config.
</p>
        </blockquote>
        <p>
Unfortunately, following the instructions in the error message doesn't help. There's
a <a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e/1c33a54539f8abf7">discussion
about this issue</a> on the Castle Project Users forum, but the gist of it is that
if you don't need to <em>resolve</em> components during application startup, this
shouldn't be an issue, and indeed it isn't – it seems to be something else. 
</p>
        <p>
In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules
instead of configuration/system.web/httpModules. 
</p>
        <p>
Although I haven't had the opportunity to dive into the technical details to understand <em>why</em> this
works, this seems to solve the problem on both Windows Vista and Windows Server 2008.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4276a194-a567-47ab-80b3-23c2813537f3" />
      </body>
      <title>Using Castle Windsor's PerWebRequest lifestyle with ASP.NET MVC on IIS7</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/17/UsingCastleWindsorsPerWebRequestLifestyleWithASPNETMVCOnIIS7.aspx</link>
      <pubDate>Tue, 17 Nov 2009 12:44:37 GMT</pubDate>
      <description>&lt;p&gt;
When using &lt;a href="http://castleproject.org/container/index.html"&gt;Castle Windsor&lt;/a&gt; in
web applications you would want to register many of your components with a lifestyle
that is associated with a single request. This is the purpose of the PerWebRequest
lifestyle.
&lt;/p&gt;
&lt;p&gt;
If you try that with ASP.NET MVC on IIS7, you are likely to receive the following
error message:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule 
&lt;br&gt;
Add '&amp;lt;add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" /&amp;gt;' to the &amp;lt;httpModules&amp;gt; section on your web.config.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Unfortunately, following the instructions in the error message doesn't help. There's
a &lt;a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e/1c33a54539f8abf7"&gt;discussion
about this issue&lt;/a&gt; on the Castle Project Users forum, but the gist of it is that
if you don't need to &lt;em&gt;resolve&lt;/em&gt; components during application startup, this
shouldn't be an issue, and indeed it isn't – it seems to be something else. 
&lt;p&gt;
In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules
instead of configuration/system.web/httpModules. 
&lt;p&gt;
Although I haven't had the opportunity to dive into the technical details to understand &lt;em&gt;why&lt;/em&gt; this
works, this seems to solve the problem on both Windows Vista and Windows Server 2008.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4276a194-a567-47ab-80b3-23c2813537f3" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=73994895-a86a-4ea4-bc41-00ed2e0bc0de</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,73994895-a86a-4ea4-bc41-00ed2e0bc0de.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,73994895-a86a-4ea4-bc41-00ed2e0bc0de.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=73994895-a86a-4ea4-bc41-00ed2e0bc0de</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The <a href="http://autofixture.codeplex.com/WorkItem/View.aspx?WorkItemId=2987">following
feature suggestion</a> was recently posted in the <a href="http://autofixture.codeplex.com/">AutoFixture</a> <a href="http://autofixture.codeplex.com/WorkItem/List.aspx">Issue
Tracker</a> board:
</p>
        <blockquote>
          <p>
"We're using AutoFixture to create random rows of data in our DB. A lot of times though,
it creates strings that are too long for the database columns. It would be nice if
the .With&lt;string&gt; method had an overload that took in a min/max length. We want
the random data, but capped at a limit.
</p>
          <p>
"fixture.Build&lt;MyObject&gt;.With(x = x.MyString, 0, 100);
</p>
          <p>
"As an aside, this is for a project that uses Nhibernate and Fluent Nhibernate, which
has these lengths already defined. I would be nice if AutoFixture could automatically
pick up on that somehow."
</p>
        </blockquote>
        <p>
I think such an feature is an excellent idea, but I don't think I will include in
AutoFixture. Why not?
</p>
        <p>
So far, I have kept the AutoFixture API pretty clean and very generic, and it is my
belief that this is one of the main reasons it is so expressive and flexible. There
are no methods that only work on specific types (such as strings), and I am reluctant
to introduce them now.
</p>
        <p>
In the last six months, I have identified a lot of specialized usage idioms that I
would love to package into a reusable library, but I think that they will pollute
the core AutoFixture API, so I'm going to put those in one or more optional 'add-on'
libraries.
</p>
        <p>
The ability to define strings that are constrained on length could be one such feature,
but rather than wait for a helper library, I will show you have you can implement
such a method yourself.
</p>
        <p>
The first thing we need is a method that can create anonymous strings given length
constraints. One possible implementation is this ConstrainedStringGenerator class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 ConstrainedStringGenerator\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  minimumLength;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  maximumLength;\par ??\par ??    \cf1 public\cf0  ConstrainedStringGenerator(\cf1 int\cf0  minimumLength, \par ??        \cf1 int\cf0  maximumLength)\par ??    \{\par ??        \cf1 if\cf0  (maximumLength &lt; 0)\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "..."\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (minimumLength &gt; maximumLength)\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "..."\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .minimumLength = minimumLength;\par ??        \cf1 this\cf0 .maximumLength = maximumLength;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 string\cf0  CreateaAnonymous(\cf1 string\cf0  seed)\par ??    \{\par ??        \cf1 var\cf0  s = \cf1 string\cf0 .Empty;\par ??        \cf1 while\cf0  (s.Length &lt; \cf1 this\cf0 .minimumLength)\par ??        \{\par ??            s += \cf4 GuidStringGenerator\cf0 .CreateAnonymous(seed);\par ??        \}\par ??        \cf1 if\cf0  (s.Length &gt; \cf1 this\cf0 .maximumLength)\par ??        \{\par ??            s = s.Substring(0, \cf1 this\cf0 .maximumLength);\par ??        \}\par ??        \cf1 return\cf0  s;\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ConstrainedStringGenerator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">int</span> minimumLength;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">int</span> maximumLength;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> ConstrainedStringGenerator(<span style="color: blue">int</span> minimumLength, </pre>
          <pre style="margin: 0px">        <span style="color: blue">int</span> maximumLength)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (maximumLength
&lt; 0)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentOutOfRangeException</span>(<span style="color: #a31515">"..."</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (minimumLength
&gt; maximumLength)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentOutOfRangeException</span>(<span style="color: #a31515">"..."</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.minimumLength
= minimumLength;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.maximumLength
= maximumLength;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">string</span> CreateaAnonymous(<span style="color: blue">string</span> seed)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> s
= <span style="color: blue">string</span>.Empty;</pre>
          <pre style="margin: 0px">        <span style="color: blue">while</span> (s.Length
&lt; <span style="color: blue">this</span>.minimumLength)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            s += <span style="color: #2b91af">GuidStringGenerator</span>.CreateAnonymous(seed);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (s.Length
&gt; <span style="color: blue">this</span>.maximumLength)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            s = s.Substring(0, <span style="color: blue">this</span>.maximumLength);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> s;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The CreateAnonymous method uses AutoFixture's GuidStringGenerator class to create
anonymous strings of the required length. For this implementation I chose a basic
algorithm, but I'm sure you can create one that is more sophisticated if you need
it.
</p>
        <p>
Th next thing we need to do is to implement the desired With method. That can be done
with an extension method works on ObjectBuilder&lt;T&gt;:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf4 ObjectBuilderExtension\par ??\cf0 \{\par ??    \cf1 public\cf0  \cf1 static\cf0  \cf4 ObjectBuilder\cf0 &lt;T&gt; With&lt;T&gt;(\par ??        \cf1 this\cf0  \cf4 ObjectBuilder\cf0 &lt;T&gt; ob,\par ??        \cf4 Expression\cf0 &lt;\cf4 Func\cf0 &lt;T, \cf1 string\cf0 &gt;&gt; propertyPicker,\par ??        \cf1 int\cf0  minimumLength,\par ??        \cf1 int\cf0  maximumLength)\par ??    \{\par ??        \cf1 var\cf0  me = (\cf4 MemberExpression\cf0 )propertyPicker.Body;\par ??        \cf1 var\cf0  name = me.Member.Name;\par ??        \cf1 var\cf0  generator =\par ??            \cf1 new\cf0  \cf4 ConstrainedStringGenerator\cf0 (\par ??                minimumLength, maximumLength);\par ??        \cf1 var\cf0  value = generator.CreateaAnonymous(name);\par ??        \cf1 return\cf0  ob.With(propertyPicker, value);\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">static</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">ObjectBuilderExtension</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: #2b91af">ObjectBuilder</span>&lt;T&gt;
With&lt;T&gt;(</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span><span style="color: #2b91af">ObjectBuilder</span>&lt;T&gt;
ob,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T, <span style="color: blue">string</span>&gt;&gt;
propertyPicker,</pre>
          <pre style="margin: 0px">        <span style="color: blue">int</span> minimumLength,</pre>
          <pre style="margin: 0px">        <span style="color: blue">int</span> maximumLength)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> me
= (<span style="color: #2b91af">MemberExpression</span>)propertyPicker.Body;</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> name
= me.Member.Name;</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> generator
=</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">ConstrainedStringGenerator</span>(</pre>
          <pre style="margin: 0px">                minimumLength, maximumLength);</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> value
= generator.CreateaAnonymous(name);</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> ob.With(propertyPicker,
value);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The method takes the same input as ObjectBuilder&lt;T&gt;'s With method, plus the
two integers that constrain the length. Note that the propertyPicker expression has
been constrained to deal only with strings.
</p>
        <p>
In this implementation, we use the ConstrainedStringGenerator class to generate the
desired value for the property, where after we can use the existing With method to
assign the value to the property in question.
</p>
        <p>
This now allows us to write Build statements like the one originally requested:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.Build&lt;\cf4 MyClass\cf0 &gt;()\par ??    .With(x =&gt; x.SomeText, 0, 100)\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.Build&lt;<span style="color: #2b91af">MyClass</span>&gt;()</pre>
          <pre style="margin: 0px">    .With(x =&gt; x.SomeText, 0, 100)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
The other part of the request, regarding NHibernate integration, I will leave to the
interested reader – mostly because I have never used NHibernate, so I have no clue
how to do it. I would, however, love to see a blog post with that addition.
</p>
        <p>
This entire example is now part of the AutoFixture test suite, so if you are interested
in looking at it in more detail, you can get it from the AutoFixture source code (available
at CodePlex).
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=73994895-a86a-4ea4-bc41-00ed2e0bc0de" />
      </body>
      <title>Creating length-constrained strings with AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,73994895-a86a-4ea4-bc41-00ed2e0bc0de.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/07/CreatingLengthconstrainedStringsWithAutoFixture.aspx</link>
      <pubDate>Sat, 07 Nov 2009 19:56:05 GMT</pubDate>
      <description>&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/WorkItem/View.aspx?WorkItemId=2987"&gt;following
feature suggestion&lt;/a&gt; was recently posted in the &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;&amp;nbsp;&lt;a href="http://autofixture.codeplex.com/WorkItem/List.aspx"&gt;Issue
Tracker&lt;/a&gt; board:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
"We're using AutoFixture to create random rows of data in our DB. A lot of times though,
it creates strings that are too long for the database columns. It would be nice if
the .With&amp;lt;string&amp;gt; method had an overload that took in a min/max length. We want
the random data, but capped at a limit.
&lt;/p&gt;
&lt;p&gt;
"fixture.Build&amp;lt;MyObject&amp;gt;.With(x = x.MyString, 0, 100);
&lt;/p&gt;
&lt;p&gt;
"As an aside, this is for a project that uses Nhibernate and Fluent Nhibernate, which
has these lengths already defined. I would be nice if AutoFixture could automatically
pick up on that somehow."
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
I think such an feature is an excellent idea, but I don't think I will include in
AutoFixture. Why not?
&lt;/p&gt;
&lt;p&gt;
So far, I have kept the AutoFixture API pretty clean and very generic, and it is my
belief that this is one of the main reasons it is so expressive and flexible. There
are no methods that only work on specific types (such as strings), and I am reluctant
to introduce them now.
&lt;/p&gt;
&lt;p&gt;
In the last six months, I have identified a lot of specialized usage idioms that I
would love to package into a reusable library, but I think that they will pollute
the core AutoFixture API, so I'm going to put those in one or more optional 'add-on'
libraries.
&lt;/p&gt;
&lt;p&gt;
The ability to define strings that are constrained on length could be one such feature,
but rather than wait for a helper library, I will show you have you can implement
such a method yourself.
&lt;/p&gt;
&lt;p&gt;
The first thing we need is a method that can create anonymous strings given length
constraints. One possible implementation is this ConstrainedStringGenerator class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 ConstrainedStringGenerator\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  minimumLength;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  maximumLength;\par ??\par ??    \cf1 public\cf0  ConstrainedStringGenerator(\cf1 int\cf0  minimumLength, \par ??        \cf1 int\cf0  maximumLength)\par ??    \{\par ??        \cf1 if\cf0  (maximumLength &amp;lt; 0)\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "..."\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (minimumLength &amp;gt; maximumLength)\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "..."\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .minimumLength = minimumLength;\par ??        \cf1 this\cf0 .maximumLength = maximumLength;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 string\cf0  CreateaAnonymous(\cf1 string\cf0  seed)\par ??    \{\par ??        \cf1 var\cf0  s = \cf1 string\cf0 .Empty;\par ??        \cf1 while\cf0  (s.Length &amp;lt; \cf1 this\cf0 .minimumLength)\par ??        \{\par ??            s += \cf4 GuidStringGenerator\cf0 .CreateAnonymous(seed);\par ??        \}\par ??        \cf1 if\cf0  (s.Length &amp;gt; \cf1 this\cf0 .maximumLength)\par ??        \{\par ??            s = s.Substring(0, \cf1 this\cf0 .maximumLength);\par ??        \}\par ??        \cf1 return\cf0  s;\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ConstrainedStringGenerator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; minimumLength;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; maximumLength;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; ConstrainedStringGenerator(&lt;span style="color: blue"&gt;int&lt;/span&gt; minimumLength, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; maximumLength)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (maximumLength
&amp;lt; 0)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"..."&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (minimumLength
&amp;gt; maximumLength)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"..."&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.minimumLength
= minimumLength;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.maximumLength
= maximumLength;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; CreateaAnonymous(&lt;span style="color: blue"&gt;string&lt;/span&gt; seed)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; s
= &lt;span style="color: blue"&gt;string&lt;/span&gt;.Empty;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;while&lt;/span&gt; (s.Length
&amp;lt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.minimumLength)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; s += &lt;span style="color: #2b91af"&gt;GuidStringGenerator&lt;/span&gt;.CreateAnonymous(seed);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (s.Length
&amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.maximumLength)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; s = s.Substring(0, &lt;span style="color: blue"&gt;this&lt;/span&gt;.maximumLength);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; s;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The CreateAnonymous method uses AutoFixture's GuidStringGenerator class to create
anonymous strings of the required length. For this implementation I chose a basic
algorithm, but I'm sure you can create one that is more sophisticated if you need
it.
&lt;/p&gt;
&lt;p&gt;
Th next thing we need to do is to implement the desired With method. That can be done
with an extension method works on ObjectBuilder&amp;lt;T&amp;gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf4 ObjectBuilderExtension\par ??\cf0 \{\par ??    \cf1 public\cf0  \cf1 static\cf0  \cf4 ObjectBuilder\cf0 &amp;lt;T&amp;gt; With&amp;lt;T&amp;gt;(\par ??        \cf1 this\cf0  \cf4 ObjectBuilder\cf0 &amp;lt;T&amp;gt; ob,\par ??        \cf4 Expression\cf0 &amp;lt;\cf4 Func\cf0 &amp;lt;T, \cf1 string\cf0 &amp;gt;&amp;gt; propertyPicker,\par ??        \cf1 int\cf0  minimumLength,\par ??        \cf1 int\cf0  maximumLength)\par ??    \{\par ??        \cf1 var\cf0  me = (\cf4 MemberExpression\cf0 )propertyPicker.Body;\par ??        \cf1 var\cf0  name = me.Member.Name;\par ??        \cf1 var\cf0  generator =\par ??            \cf1 new\cf0  \cf4 ConstrainedStringGenerator\cf0 (\par ??                minimumLength, maximumLength);\par ??        \cf1 var\cf0  value = generator.CreateaAnonymous(name);\par ??        \cf1 return\cf0  ob.With(propertyPicker, value);\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ObjectBuilderExtension&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ObjectBuilder&lt;/span&gt;&amp;lt;T&amp;gt;
With&amp;lt;T&amp;gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ObjectBuilder&lt;/span&gt;&amp;lt;T&amp;gt;
ob,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;
propertyPicker,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; minimumLength,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; maximumLength)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; me
= (&lt;span style="color: #2b91af"&gt;MemberExpression&lt;/span&gt;)propertyPicker.Body;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; name
= me.Member.Name;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; generator
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ConstrainedStringGenerator&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; minimumLength, maximumLength);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; value
= generator.CreateaAnonymous(name);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; ob.With(propertyPicker,
value);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The method takes the same input as ObjectBuilder&amp;lt;T&amp;gt;'s With method, plus the
two integers that constrain the length. Note that the propertyPicker expression has
been constrained to deal only with strings.
&lt;/p&gt;
&lt;p&gt;
In this implementation, we use the ConstrainedStringGenerator class to generate the
desired value for the property, where after we can use the existing With method to
assign the value to the property in question.
&lt;/p&gt;
&lt;p&gt;
This now allows us to write Build statements like the one originally requested:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.Build&amp;lt;\cf4 MyClass\cf0 &amp;gt;()\par ??    .With(x =&amp;gt; x.SomeText, 0, 100)\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(x =&amp;gt; x.SomeText, 0, 100)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The other part of the request, regarding NHibernate integration, I will leave to the
interested reader – mostly because I have never used NHibernate, so I have no clue
how to do it. I would, however, love to see a blog post with that addition.
&lt;/p&gt;
&lt;p&gt;
This entire example is now part of the AutoFixture test suite, so if you are interested
in looking at it in more detail, you can get it from the AutoFixture source code (available
at CodePlex).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=73994895-a86a-4ea4-bc41-00ed2e0bc0de" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,73994895-a86a-4ea4-bc41-00ed2e0bc0de.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2b0fb814-4d75-422b-a104-896bf3de1ed4</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2b0fb814-4d75-422b-a104-896bf3de1ed4.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2b0fb814-4d75-422b-a104-896bf3de1ed4.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2b0fb814-4d75-422b-a104-896bf3de1ed4</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> beta 1 is now available
on the CodePlex site! We have been using AutoFixture quite intensively in <a href="http://www.safewhere.net">Safewhere</a> for
almost half a year now, and the core of it has turned out to be stable and much more
powerful than I originally imagined.
</p>
        <p>
During that period, I have discovered and fixed a few bugs, but the most positive
experience has been how extended usage has inspired us to come up with numerous ideas
to new cool features. Some of these features are already implemented in the current
release, and the rest are <a href="http://autofixture.codeplex.com/WorkItem/List.aspx">listed
on the AutoFixture site</a>.
</p>
        <p>
The <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29097">beta
1 release page</a> has more details about this particular release.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2b0fb814-4d75-422b-a104-896bf3de1ed4" />
      </body>
      <title>AutoFixture beta 1</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2b0fb814-4d75-422b-a104-896bf3de1ed4.aspx</guid>
      <link>http://blog.ploeh.dk/2009/10/31/AutoFixtureBeta1.aspx</link>
      <pubDate>Sat, 31 Oct 2009 08:59:43 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; beta 1 is now available
on the CodePlex site! We have been using AutoFixture quite intensively in &lt;a href="http://www.safewhere.net"&gt;Safewhere&lt;/a&gt; for
almost half a year now, and the core of it has turned out to be stable and much more
powerful than I originally imagined.
&lt;/p&gt;
&lt;p&gt;
During that period, I have discovered and fixed a few bugs, but the most positive
experience has been how extended usage has inspired us to come up with numerous ideas
to new cool features. Some of these features are already implemented in the current
release, and the rest are &lt;a href="http://autofixture.codeplex.com/WorkItem/List.aspx"&gt;listed
on the AutoFixture site&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29097"&gt;beta
1 release page&lt;/a&gt; has more details about this particular release.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2b0fb814-4d75-422b-a104-896bf3de1ed4" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2b0fb814-4d75-422b-a104-896bf3de1ed4.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=43e6e4e3-6e34-4100-9106-3c9fa12b9e8c</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,43e6e4e3-6e34-4100-9106-3c9fa12b9e8c.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,43e6e4e3-6e34-4100-9106-3c9fa12b9e8c.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=43e6e4e3-6e34-4100-9106-3c9fa12b9e8c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A few months ago I described how you can use <a href="http://autofixture.codeplex.com/">AutoFixture</a>'s <a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx">With
method</a> to assign property values as part of building up an anonymous variable.
In that scenario, the With method is used to explicitly assign a particular, pre-defined
value to a property.
</p>
        <p>
There's another overload of the With method that <em>doesn't</em> take an explicit
value, but rather uses AutoFixture to create an anonymous value for the property.
So what's the deal with that if AutoFixture's default behavior is to assign anonymous
values to all writable properties?
</p>
        <p>
In short it's an opt-in mechanism that only makes sense if you decide to opt out of
the AutoProperties features.
</p>
        <p>
As always, let's look at an example. This time, I've decided to show you a slightly
more realistic example so that you can get an idea of how AutoFixture can be used
to aid in unit testing. This also means that the example is going to be a little more
complex than usual, but it's still simple.
</p>
        <p>
Imagine that we wish to test that an ASP.NET MVC Controller Action returns the correct
result. More specifically, we wish to test that the Profile method on MyController
returns a ViewResult with the correct Model (the current user's name, to make things
interesing).
</p>
        <p>
Here's the entire test. It may look more complicated than it is – it's really only
10 lines of code, but I had to break them up to prevent unpleasant wrapping if your
screen is narrow.
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ProfileWillReturnResultWithCorrectUserName()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();</pre>
          <pre style="margin: 0px">    fixture.Customize&lt;<span style="color: #2b91af">ControllerContext</span>&gt;(ob
=&gt; ob</pre>
          <pre style="margin: 0px">        .OmitAutoProperties()</pre>
          <pre style="margin: 0px">        .With(cc =&gt; cc.HttpContext));</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> expectedUserName
= </pre>
          <pre style="margin: 0px">        fixture.CreateAnonymous(<span style="color: #a31515">"UserName"</span>);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> httpCtxStub
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt;();</pre>
          <pre style="margin: 0px">    httpCtxStub.SetupGet(x =&gt; x.User).Returns(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">GenericPrincipal</span>(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">GenericIdentity</span>(expectedUserName), <span style="color: blue">null</span>));</pre>
          <pre style="margin: 0px">    fixture.Register(httpCtxStub.Object);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.Build&lt;<span style="color: #2b91af">MyController</span>&gt;()</pre>
          <pre style="margin: 0px">        .OmitAutoProperties()</pre>
          <pre style="margin: 0px">        .With(c =&gt; c.ControllerContext)</pre>
          <pre style="margin: 0px">        .CreateAnonymous();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">ViewResult</span> result
= sut.Profile();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> actual
= result.ViewData.Model;</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual(expectedUserName,
actual, <span style="color: #a31515">"User"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Apart from AutoFixture, I'm also making use of <a href="http://code.google.com/p/moq/">Moq</a> to
stub out HttpContextBase.
</p>
        <p>
You can see the Anonymous With method in two different places: in the call to <a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx">Customize</a> and
when the <a href="http://xunitpatterns.com/SUT.html">SUT</a> is being built. In both
cases you can see that the call to With follows a call to OmitAutoProperties. In other
words: we are telling AutoFixture that we don't want any of the writable properties
to be assigned a value <em>except</em> the one we identify.
</p>
        <p>
Let me highlight some parts of the test.
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">fixture.Customize&lt;<span style="color: #2b91af">ControllerContext</span>&gt;(ob
=&gt; ob</pre>
          <pre style="margin: 0px">    .OmitAutoProperties()</pre>
          <pre style="margin: 0px">    .With(cc =&gt; cc.HttpContext));</pre>
        </div>
        <p>
This line of code instructs AutoFixture to always create a ControllerContext in a
particular way: I don't want to use AutoProperties here, because ControllerContext
has a lot of writable properties of abstract types, and that would require me to set
up a lot of Test Doubles if I had to assign values to all of those. It's much easier
to simply opt out of this mechanism. However, I <em>would</em> like to have the HttpContext
property assigned, but I don't care about the value in this statement, so the With
method simply states that AutoFixture should assign a value according to whatever
rule it has for creating instances of HttpContextBase.
</p>
        <p>
I can now set up a Stub that populates the User property of HttpContextBase:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> httpCtxStub
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">HttpContextBase</span>&gt;();</pre>
          <pre style="margin: 0px">httpCtxStub.SetupGet(x =&gt; x.User).Returns(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">GenericPrincipal</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">GenericIdentity</span>(expectedUserName), <span style="color: blue">null</span>));</pre>
          <pre style="margin: 0px">fixture.Register(httpCtxStub.Object);</pre>
        </div>
        <p>
This is registered with the fixture instance which closes the loop to the previous
customization.
</p>
        <p>
I can now create an instance of my SUT. Once more, I don't want to have to set up
a lot of irrelevant properties on MyController, so I opt out of AutoProperties and
then explicitly opt in on the ControllerContext. This will cause AutoFixture to automatically
populate the ControllerContext with the HttpContext Stub:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= fixture.Build&lt;<span style="color: #2b91af">MyController</span>&gt;()</pre>
          <pre style="margin: 0px">    .OmitAutoProperties()</pre>
          <pre style="margin: 0px">    .With(c =&gt; c.ControllerContext)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
For completeness' sake, here's the MyController class that I am testing:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">MyController</span> : <span style="color: #2b91af">Controller</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">ViewResult</span> Profile()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">object</span> userName
= <span style="color: blue">this</span>.User.Identity.Name;</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.View(userName);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This test may seem complex, but it really accomplishes a lot in only 10 lines of code,
considering that ASP.NET MVC Controllers with a working HttpContext are not particularly
trivial to set up.
</p>
        <p>
In summary, this With method overload lets you opt in on one or more explicitly identified
properties when you have otherwise decided to omit AutoProperties. As all the other
Builder methods, this method can also be chained.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=43e6e4e3-6e34-4100-9106-3c9fa12b9e8c" />
      </body>
      <title>Anonymous With</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,43e6e4e3-6e34-4100-9106-3c9fa12b9e8c.aspx</guid>
      <link>http://blog.ploeh.dk/2009/10/26/AnonymousWith.aspx</link>
      <pubDate>Mon, 26 Oct 2009 20:26:49 GMT</pubDate>
      <description>&lt;p&gt;
A few months ago I described how you can use &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;'s &lt;a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx"&gt;With
method&lt;/a&gt; to assign property values as part of building up an anonymous variable.
In that scenario, the With method is used to explicitly assign a particular, pre-defined
value to a property.
&lt;/p&gt;
&lt;p&gt;
There's another overload of the With method that &lt;em&gt;doesn't&lt;/em&gt; take an explicit
value, but rather uses AutoFixture to create an anonymous value for the property.
So what's the deal with that if AutoFixture's default behavior is to assign anonymous
values to all writable properties?
&lt;/p&gt;
&lt;p&gt;
In short it's an opt-in mechanism that only makes sense if you decide to opt out of
the AutoProperties features.
&lt;/p&gt;
&lt;p&gt;
As always, let's look at an example. This time, I've decided to show you a slightly
more realistic example so that you can get an idea of how AutoFixture can be used
to aid in unit testing. This also means that the example is going to be a little more
complex than usual, but it's still simple.
&lt;/p&gt;
&lt;p&gt;
Imagine that we wish to test that an ASP.NET MVC Controller Action returns the correct
result. More specifically, we wish to test that the Profile method on MyController
returns a ViewResult with the correct Model (the current user's name, to make things
interesing).
&lt;/p&gt;
&lt;p&gt;
Here's the entire test. It may look more complicated than it is – it's really only
10 lines of code, but I had to break them up to prevent unpleasant wrapping if your
screen is narrow.
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ProfileWillReturnResultWithCorrectUserName()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Customize&amp;lt;&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt;&amp;gt;(ob
=&amp;gt; ob&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .OmitAutoProperties()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(cc =&amp;gt; cc.HttpContext));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; expectedUserName
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.CreateAnonymous(&lt;span style="color: #a31515"&gt;"UserName"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; httpCtxStub
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HttpContextBase&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; httpCtxStub.SetupGet(x =&amp;gt; x.User).Returns(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;GenericPrincipal&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;GenericIdentity&lt;/span&gt;(expectedUserName), &lt;span style="color: blue"&gt;null&lt;/span&gt;));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Register(httpCtxStub.Object);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyController&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .OmitAutoProperties()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(c =&amp;gt; c.ControllerContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ViewResult&lt;/span&gt; result
= sut.Profile();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; actual
= result.ViewData.Model;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual(expectedUserName,
actual, &lt;span style="color: #a31515"&gt;"User"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Apart from AutoFixture, I'm also making use of &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; to
stub out HttpContextBase.
&lt;/p&gt;
&lt;p&gt;
You can see the Anonymous With method in two different places: in the call to &lt;a href="http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx"&gt;Customize&lt;/a&gt; and
when the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt; is being built. In both
cases you can see that the call to With follows a call to OmitAutoProperties. In other
words: we are telling AutoFixture that we don't want any of the writable properties
to be assigned a value &lt;em&gt;except&lt;/em&gt; the one we identify.
&lt;/p&gt;
&lt;p&gt;
Let me highlight some parts of the test.
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;fixture.Customize&amp;lt;&lt;span style="color: #2b91af"&gt;ControllerContext&lt;/span&gt;&amp;gt;(ob
=&amp;gt; ob&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .OmitAutoProperties()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(cc =&amp;gt; cc.HttpContext));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This line of code instructs AutoFixture to always create a ControllerContext in a
particular way: I don't want to use AutoProperties here, because ControllerContext
has a lot of writable properties of abstract types, and that would require me to set
up a lot of Test Doubles if I had to assign values to all of those. It's much easier
to simply opt out of this mechanism. However, I &lt;em&gt;would&lt;/em&gt; like to have the HttpContext
property assigned, but I don't care about the value in this statement, so the With
method simply states that AutoFixture should assign a value according to whatever
rule it has for creating instances of HttpContextBase.
&lt;/p&gt;
&lt;p&gt;
I can now set up a Stub that populates the User property of HttpContextBase:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; httpCtxStub
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;HttpContextBase&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;httpCtxStub.SetupGet(x =&amp;gt; x.User).Returns(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;GenericPrincipal&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;GenericIdentity&lt;/span&gt;(expectedUserName), &lt;span style="color: blue"&gt;null&lt;/span&gt;));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.Register(httpCtxStub.Object);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is registered with the fixture instance which closes the loop to the previous
customization.
&lt;/p&gt;
&lt;p&gt;
I can now create an instance of my SUT. Once more, I don't want to have to set up
a lot of irrelevant properties on MyController, so I opt out of AutoProperties and
then explicitly opt in on the ControllerContext. This will cause AutoFixture to automatically
populate the ControllerContext with the HttpContext Stub:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyController&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .OmitAutoProperties()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(c =&amp;gt; c.ControllerContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
For completeness' sake, here's the MyController class that I am testing:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyController&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ViewResult&lt;/span&gt; Profile()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;object&lt;/span&gt; userName
= &lt;span style="color: blue"&gt;this&lt;/span&gt;.User.Identity.Name;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.View(userName);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This test may seem complex, but it really accomplishes a lot in only 10 lines of code,
considering that ASP.NET MVC Controllers with a working HttpContext are not particularly
trivial to set up.
&lt;/p&gt;
&lt;p&gt;
In summary, this With method overload lets you opt in on one or more explicitly identified
properties when you have otherwise decided to omit AutoProperties. As all the other
Builder methods, this method can also be chained.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=43e6e4e3-6e34-4100-9106-3c9fa12b9e8c" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,43e6e4e3-6e34-4100-9106-3c9fa12b9e8c.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=5c389092-f834-4882-b27d-73f5e6846d52</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,5c389092-f834-4882-b27d-73f5e6846d52.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,5c389092-f834-4882-b27d-73f5e6846d52.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=5c389092-f834-4882-b27d-73f5e6846d52</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://danielfrost.dk/">Daniel Frost</a> has published a podcast where he
discusses WCF with me. It's about half an hour and in Danish. <a href="http://danielfrost.dk/post/Frosts-Podcast-Show-4-e28093-Mark-Seemann-om-WCF.aspx">Hear
it here</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=5c389092-f834-4882-b27d-73f5e6846d52" />
      </body>
      <title>WCF Podcast with me</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,5c389092-f834-4882-b27d-73f5e6846d52.aspx</guid>
      <link>http://blog.ploeh.dk/2009/10/24/WCFPodcastWithMe.aspx</link>
      <pubDate>Sat, 24 Oct 2009 01:52:18 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://danielfrost.dk/"&gt;Daniel Frost&lt;/a&gt; has published a podcast where he
discusses WCF with me. It's about half an hour and in Danish. &lt;a href="http://danielfrost.dk/post/Frosts-Podcast-Show-4-e28093-Mark-Seemann-om-WCF.aspx"&gt;Hear
it here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=5c389092-f834-4882-b27d-73f5e6846d52" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,5c389092-f834-4882-b27d-73f5e6846d52.aspx</comments>
      <category>Miscellaneous</category>
      <category>Services</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=6caf04d0-c866-492e-8f1e-289af8739a69</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=6caf04d0-c866-492e-8f1e-289af8739a69</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For the last few months I've been writing a book for Manning tentatively titled <em>Dependency
Injection in .NET</em>. The <a href="http://www.manning.com/seemann/">page about the
book</a> is now live at the <a href="http://www.manning.com/">Manning</a> web site
where you can read more about it and, if you would like, purchase an Early Access
edition and read the chapters as they are being written.
</p>
        <p>
If you have ever wanted to learn about Dependency Injection (DI) related to .NET,
here's your chance!
</p>
        <p>
At the moment I'm about a third of the way into the book, so there's still some way
to go, but I hope to be done with it in 2010.
</p>
        <p>
If you decide to purchase an Early Access edition, I'd love to receive your feedback
in the online forum.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6caf04d0-c866-492e-8f1e-289af8739a69" />
      </body>
      <title>Writing a book</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</guid>
      <link>http://blog.ploeh.dk/2009/10/05/WritingABook.aspx</link>
      <pubDate>Mon, 05 Oct 2009 18:13:50 GMT</pubDate>
      <description>&lt;p&gt;
For the last few months I've been writing a book for Manning tentatively titled &lt;em&gt;Dependency
Injection in .NET&lt;/em&gt;. The &lt;a href="http://www.manning.com/seemann/"&gt;page about the
book&lt;/a&gt; is now live at the &lt;a href="http://www.manning.com/"&gt;Manning&lt;/a&gt; web site
where you can read more about it and, if you would like, purchase an Early Access
edition and read the chapters as they are being written.
&lt;/p&gt;
&lt;p&gt;
If you have ever wanted to learn about Dependency Injection (DI) related to .NET,
here's your chance!
&lt;/p&gt;
&lt;p&gt;
At the moment I'm about a third of the way into the book, so there's still some way
to go, but I hope to be done with it in 2010.
&lt;/p&gt;
&lt;p&gt;
If you decide to purchase an Early Access edition, I'd love to receive your feedback
in the online forum.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6caf04d0-c866-492e-8f1e-289af8739a69" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=9ca3fd0d-54be-4fad-9115-ebb84a3ff912</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,9ca3fd0d-54be-4fad-9115-ebb84a3ff912.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,9ca3fd0d-54be-4fad-9115-ebb84a3ff912.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=9ca3fd0d-54be-4fad-9115-ebb84a3ff912</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The SOLID principles of OOD as <a href="http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod">originally
put forth by Robert C. Martin</a> make for such a catchy acronym, although they seem
to originally have been spelled SOLDI.
</p>
        <p>
In any case I've lately been thinking a bit about these principles and it seems to
me that the Single Responsibility Principle (SRP) and the Interface Segregation Principle
(ISP) seem to be very much related. In essence you could say that the ISP is simply
SRP applied to interfaces.
</p>
        <p>
The notion underlying both is that a type should deal with only a single concept.
Whether that applies to the public API or the internal implementation is less relevant
because a corollary to the Liskov Substitution Principle (LSP) and Dependency Inversion
Principle (DIP) is that we shouldn't really care about the internals (unless we are
actually implementing, that is).
</p>
        <p>
The API is what matters.
</p>
        <p>
Although I do understand the subtle differences between SRP and ISP I think they are
so closely related that one of them is really redundant. We can remove the ISP and
still have a fairly good acronym: SOLD (although SOLID is still better).
</p>
        <p>
There's one principle that I think is missing from this set: The principle about Command/Query
Separation (CQS). In my opinion, this is a very important principle that should be
highlighted more than is currently the case.
</p>
        <p>
If we add CQS to SOLD, we are left with some less attractive acronyms:
</p>
        <ul>
          <li>
SCOLD</li>
          <li>
COLDS</li>
          <li>
CLODS</li>
        </ul>
        <p>
Not nearly as confidence-inspiring acronyms as SOLID, but nonetheless, I'm striving
to write COLDS code.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9ca3fd0d-54be-4fad-9115-ebb84a3ff912" />
      </body>
      <title>SOLID or COLDS?</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,9ca3fd0d-54be-4fad-9115-ebb84a3ff912.aspx</guid>
      <link>http://blog.ploeh.dk/2009/09/29/SOLIDOrCOLDS.aspx</link>
      <pubDate>Tue, 29 Sep 2009 19:38:42 GMT</pubDate>
      <description>&lt;p&gt;
The SOLID principles of OOD as &lt;a href="http://www.butunclebob.com/ArticleS.UncleBob.PrinciplesOfOod"&gt;originally
put forth by Robert C. Martin&lt;/a&gt; make for such a catchy acronym, although they seem
to originally have been spelled SOLDI.
&lt;/p&gt;
&lt;p&gt;
In any case I've lately been thinking a bit about these principles and it seems to
me that the Single Responsibility Principle (SRP) and the Interface Segregation Principle
(ISP) seem to be very much related. In essence you could say that the ISP is simply
SRP applied to interfaces.
&lt;/p&gt;
&lt;p&gt;
The notion underlying both is that a type should deal with only a single concept.
Whether that applies to the public API or the internal implementation is less relevant
because a corollary to the Liskov Substitution Principle (LSP) and Dependency Inversion
Principle (DIP) is that we shouldn't really care about the internals (unless we are
actually implementing, that is).
&lt;/p&gt;
&lt;p&gt;
The API is what matters.
&lt;/p&gt;
&lt;p&gt;
Although I do understand the subtle differences between SRP and ISP I think they are
so closely related that one of them is really redundant. We can remove the ISP and
still have a fairly good acronym: SOLD (although SOLID is still better).
&lt;/p&gt;
&lt;p&gt;
There's one principle that I think is missing from this set: The principle about Command/Query
Separation (CQS). In my opinion, this is a very important principle that should be
highlighted more than is currently the case.
&lt;/p&gt;
&lt;p&gt;
If we add CQS to SOLD, we are left with some less attractive acronyms:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
SCOLD&lt;/li&gt;
&lt;li&gt;
COLDS&lt;/li&gt;
&lt;li&gt;
CLODS&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Not nearly as confidence-inspiring acronyms as SOLID, but nonetheless, I'm striving
to write COLDS code.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9ca3fd0d-54be-4fad-9115-ebb84a3ff912" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,9ca3fd0d-54be-4fad-9115-ebb84a3ff912.aspx</comments>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=0b1d8171-002d-49f9-be17-ee0007333451</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,0b1d8171-002d-49f9-be17-ee0007333451.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,0b1d8171-002d-49f9-be17-ee0007333451.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=0b1d8171-002d-49f9-be17-ee0007333451</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In the <a href="http://blog.ploeh.dk/2009/08/25/DoRedux.aspx">previous post</a> on <a href="http://autofixture.codeplex.com/">AutoFixture</a>,
I demonstrated how it's possible to use a customized Builder to perform complex initialization
when requesting an instance of a particular type. To recap, this was the solution
I described:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClass\cf0 &gt;();\par ??\cf1 var\cf0  mvm = fixture.Build&lt;\cf4 MyViewModel\cf0 &gt;()\par ??    .Do(x =&gt; x.AvailableItems.Add(mc))\par ??    .With(x =&gt; x.SelectedItem, mc)\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mvm
= fixture.Build&lt;<span style="color: #2b91af">MyViewModel</span>&gt;()</pre>
          <pre style="margin: 0px">    .Do(x =&gt; x.AvailableItems.Add(mc))</pre>
          <pre style="margin: 0px">    .With(x =&gt; x.SelectedItem, mc)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
This code first creates an anonymous instance of MyClass that can be added to MyViewModel.
It then initializes a Builder for a specific instance of MyViewModel, instructing
it to
</p>
        <ol>
          <li>
add the anonymous MyClass instance to the list of AvailableItems 
</li>
          <li>
assign the same instance to the SelectedItem property</li>
        </ol>
        <p>
While this works splendidly, it can get tiresome to write the same customization over
and over again if you need to create multiple instances of the same type. It also
violate the DRY principle.
</p>
        <p>
When this is the case, you can alternatively register a customized Builder pipeline
for the type in question (in this case MyViewModel). This is done with the Customize
method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClass\cf0 &gt;();\par ??fixture.Customize&lt;\cf4 MyViewModel\cf0 &gt;(ob =&gt; ob\par ??    .Do(x =&gt; x.AvailableItems.Add(mc))\par ??    .With(x =&gt; x.SelectedItem, mc));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">fixture.Customize&lt;<span style="color: #2b91af">MyViewModel</span>&gt;(ob
=&gt; ob</pre>
          <pre style="margin: 0px">    .Do(x =&gt; x.AvailableItems.Add(mc))</pre>
          <pre style="margin: 0px">    .With(x =&gt; x.SelectedItem, mc));</pre>
        </div>
        <p>
The Customize method takes as input a function that provides an initial ObjectBuilder
as input, and returns a new, customized ObjectBuilder as output. This function is
registered with the type, so that each time an anonymous instance of the type is requested,
the customized ObjectBuilder will be used to create the instance.
</p>
        <p>
In the example, I customize the supplied ObjectBuilder (<em>ob</em>) in exactly the
same way as before, but instead of invoking CreateAnonymous, I simply return the customized
ObjectBuilder to the Fixture instance. It then saves this customized ObjectBuilder
for later use.
</p>
        <p>
With this customization, what before failed now succeeds:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.CreateAnonymous&lt;\cf4 MyViewModel\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mvm
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyViewModel</span>&gt;();</pre>
        </div>
        <p>
The Customize method is the core method for customizing AutoFixture. Most other customization
methods (like Register) are simply convenience methods that wraps Customize. It is
a very powerful method that can be used to define some very specific Builder algorithms
for particular types.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0b1d8171-002d-49f9-be17-ee0007333451" />
      </body>
      <title>Customizing A Type's Builder With AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,0b1d8171-002d-49f9-be17-ee0007333451.aspx</guid>
      <link>http://blog.ploeh.dk/2009/09/22/CustomizingATypesBuilderWithAutoFixture.aspx</link>
      <pubDate>Tue, 22 Sep 2009 14:53:48 GMT</pubDate>
      <description>&lt;p&gt;
In the &lt;a href="http://blog.ploeh.dk/2009/08/25/DoRedux.aspx"&gt;previous post&lt;/a&gt; on &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;,
I demonstrated how it's possible to use a customized Builder to perform complex initialization
when requesting an instance of a particular type. To recap, this was the solution
I described:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClass\cf0 &amp;gt;();\par ??\cf1 var\cf0  mvm = fixture.Build&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;()\par ??    .Do(x =&amp;gt; x.AvailableItems.Add(mc))\par ??    .With(x =&amp;gt; x.SelectedItem, mc)\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mvm
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Do(x =&amp;gt; x.AvailableItems.Add(mc))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(x =&amp;gt; x.SelectedItem, mc)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This code first creates an anonymous instance of MyClass that can be added to MyViewModel.
It then initializes a Builder for a specific instance of MyViewModel, instructing
it to
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
add the anonymous MyClass instance to the list of AvailableItems 
&lt;li&gt;
assign the same instance to the SelectedItem property&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
While this works splendidly, it can get tiresome to write the same customization over
and over again if you need to create multiple instances of the same type. It also
violate the DRY principle.
&lt;/p&gt;
&lt;p&gt;
When this is the case, you can alternatively register a customized Builder pipeline
for the type in question (in this case MyViewModel). This is done with the Customize
method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClass\cf0 &amp;gt;();\par ??fixture.Customize&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;(ob =&amp;gt; ob\par ??    .Do(x =&amp;gt; x.AvailableItems.Add(mc))\par ??    .With(x =&amp;gt; x.SelectedItem, mc));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.Customize&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;(ob
=&amp;gt; ob&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Do(x =&amp;gt; x.AvailableItems.Add(mc))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(x =&amp;gt; x.SelectedItem, mc));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The Customize method takes as input a function that provides an initial ObjectBuilder
as input, and returns a new, customized ObjectBuilder as output. This function is
registered with the type, so that each time an anonymous instance of the type is requested,
the customized ObjectBuilder will be used to create the instance.
&lt;/p&gt;
&lt;p&gt;
In the example, I customize the supplied ObjectBuilder (&lt;em&gt;ob&lt;/em&gt;) in exactly the
same way as before, but instead of invoking CreateAnonymous, I simply return the customized
ObjectBuilder to the Fixture instance. It then saves this customized ObjectBuilder
for later use.
&lt;/p&gt;
&lt;p&gt;
With this customization, what before failed now succeeds:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.CreateAnonymous&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mvm
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The Customize method is the core method for customizing AutoFixture. Most other customization
methods (like Register) are simply convenience methods that wraps Customize. It is
a very powerful method that can be used to define some very specific Builder algorithms
for particular types.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0b1d8171-002d-49f9-be17-ee0007333451" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,0b1d8171-002d-49f9-be17-ee0007333451.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=027e9d81-081f-4c81-b9d6-f922550cd2fa</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,027e9d81-081f-4c81-b9d6-f922550cd2fa.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,027e9d81-081f-4c81-b9d6-f922550cd2fa.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=027e9d81-081f-4c81-b9d6-f922550cd2fa</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Yesterday I released version .8.6 of <a href="http://autofixture.codeplex.com/">AutoFixture</a>.
It is a minor release that simply adds some new features.
</p>
        <p>
There are some minor breaking changes (documented on the <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=33256">release
page</a>), but they only affect supporting classes and don't touch on any of the code
examples I have so far published. In other words, if you are using AutoFixture's fluent
interface, your code should still compile.
</p>
        <p>
Please go ahead and download it and use it. As always, comments and questions are
welcome, either here or in the <a href="http://autofixture.codeplex.com/Thread/List.aspx">forum</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=027e9d81-081f-4c81-b9d6-f922550cd2fa" />
      </body>
      <title>AutoFixture .8.6 Released</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,027e9d81-081f-4c81-b9d6-f922550cd2fa.aspx</guid>
      <link>http://blog.ploeh.dk/2009/09/21/AutoFixture86Released.aspx</link>
      <pubDate>Mon, 21 Sep 2009 17:37:36 GMT</pubDate>
      <description>&lt;p&gt;
Yesterday I released version .8.6 of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;.
It is a minor release that simply adds some new features.
&lt;/p&gt;
&lt;p&gt;
There are some minor breaking changes (documented on the &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=33256"&gt;release
page&lt;/a&gt;), but they only affect supporting classes and don't touch on any of the code
examples I have so far published. In other words, if you are using AutoFixture's fluent
interface, your code should still compile.
&lt;/p&gt;
&lt;p&gt;
Please go ahead and download it and use it. As always, comments and questions are
welcome, either here or in the &lt;a href="http://autofixture.codeplex.com/Thread/List.aspx"&gt;forum&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=027e9d81-081f-4c81-b9d6-f922550cd2fa" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,027e9d81-081f-4c81-b9d6-f922550cd2fa.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=73a82937-3edf-4e01-ae35-273a93d68160</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=73a82937-3edf-4e01-ae35-273a93d68160</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel
and I recently had that problem and we couldn't find any guidance on this topic, so
now that we have a solution, I thought I'd share it.
</p>
        <p>
The problem is simple: We needed a link that invoked some server side code and updated
the text of the link itself based on the result of the operation. Here is a simplified
example:
</p>
        <p>
          <a href="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_2.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_thumb.png" width="267" height="75" />
          </a>
        </p>
        <p>
Each time you click the link, it should invoke a Controller Action and return a new
number that should appear as the link text.
</p>
        <p>
This is pretty simple to implement once you know how. The first thing to realize is
that the link and all the AJAX stuff must be placed in a user control. The only thing
that needs to go into the containing page is the containing element itself:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &lt;\cf3 h2\cf1 &gt;\cf0 Self-updating AJAX link\cf1 &lt;/\cf3 h2\cf1 &gt;\par ??\cf0 Click the link to update the number:\par ??\cf1 &lt;\cf3 span\cf0  \cf5 id\cf1 ="thespan"&gt;\par ??\cf0     \cb6\highlight6 &lt;%\cb0\highlight0  \cf1 this\cf0 .Html.RenderPartial(\cf3 "NumberAjaxUserControl"\cf0 ); \cb6\highlight6 %&gt;\par ??\cf1\cb0\highlight0 &lt;/\cf3 span\cf1 &gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">h2</span>
            <span style="color: blue">&gt;</span>Self-updating
AJAX link<span style="color: blue">&lt;/</span><span style="color: #a31515">h2</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">Click the link to update the number:</pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">span</span>
            <span style="color: red">id</span>
            <span style="color: blue">="thespan"&gt;</span>
          </pre>
          <pre style="margin: 0px">    <span style="background: #ffee62">&lt;%</span><span style="color: blue">this</span>.Html.RenderPartial(<span style="color: #a31515">"NumberAjaxUserControl"</span>); <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">span</span>
            <span style="color: blue">&gt;</span>
          </pre>
        </div>
        <p>
Notice the <em>id</em> of the span element – this same <em>id</em> will be referenced
from the user control.
</p>
        <p>
To bootstrap this view, the Controller Action for the page contains code that assigns
an initial value to the number (in this case <em>1</em>):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 ActionResult\cf0  Index()\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = 1.ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .View();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">ActionResult</span> Index()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>]
= 1.ToString();</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span><span style="color: blue">this</span>.View();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
To keep the example simple, I simply add the number to the ViewData dictionary, but
in any production implementation, I would opt to use a strongly typed ViewModel instead.
</p>
        <p>
The NumberAjaxUserControl itself only contains the definition of the AJAX link:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red43\green145\blue175;}??\fs20 \cb2\highlight2 &lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Control\cf0  \cf6 Language\cf3 ="C#"\cf0  \cf6 Inherits\cf3 ="System.Web.Mvc.ViewUserControl"\cf0  \cb2\highlight2 %&gt;\par ??&lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Import\cf0  \cf6 Namespace\cf3 ="System.Web.Mvc.Ajax"\cf0  \cb2\highlight2 %&gt;\par ??&lt;%\cf3\cb0\highlight0 =\cf0  \cf3 this\cf0 .Ajax.ActionLink((\cf3 string\cf0 )\cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ],\par ??    \cf5 "GetNext"\cf0 ,\par ??    \cf3 new\cf0  \{ number = \cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ] \}, \par ??    \cf3 new\cf0  \cf7 AjaxOptions\cf0  \{ UpdateTargetId = \cf5 "thespan"\cf0  \})\cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">@</span>
            <span style="color: #a31515">Control</span>
            <span style="color: red">Language</span>
            <span style="color: blue">="C#"</span>
            <span style="color: red">Inherits</span>
            <span style="color: blue">="System.Web.Mvc.ViewUserControl"</span>
            <span style="background: #ffee62">%&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">@</span>
            <span style="color: #a31515">Import</span>
            <span style="color: red">Namespace</span>
            <span style="color: blue">="System.Web.Mvc.Ajax"</span>
            <span style="background: #ffee62">%&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">=</span>
            <span style="color: blue">this</span>.Ajax.ActionLink((<span style="color: blue">string</span>)<span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>],</pre>
          <pre style="margin: 0px">    <span style="color: #a31515">"GetNext"</span>,</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span> {
number = <span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>]
}, </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">AjaxOptions</span> {
UpdateTargetId = <span style="color: #a31515">"thespan"</span> })<span style="background: #ffee62">%&gt;</span></pre>
        </div>
        <p>
The first parameter to the ActionLink method is simply the current number to render
as the link text. Since I'm using the untyped ViewData dictionary for this example,
I need to cast it to a string.
</p>
        <p>
The next parameter ("GetNext") indicates the Controller Action to invoke when the
link is clicked – I will cover that shortly.
</p>
        <p>
The third parameter is a Route Value that specifies that the parameter <em>number</em> with
the correct value will be supplied to the GetNext Controller Action. It uses the number
stored in ViewData.
</p>
        <p>
The last parameter indicates the <em>id</em> of the element to update. Recall from
before that this name was "thespan".
</p>
        <p>
The only missing piece now is the GetNext Controller Action:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 PartialViewResult\cf0  GetNext(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = (number + 1).ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .PartialView(\cf5 "NumberAjaxUserControl"\cf0 );\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">PartialViewResult</span> GetNext(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.ViewData[<span style="color: #a31515">"number"</span>]
= (number + 1).ToString();</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span><span style="color: blue">this</span>.PartialView(<span style="color: #a31515">"NumberAjaxUserControl"</span>);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this example I simply chose to increment the number by one, but I'm sure you can
imagine that this method could just as well perform a database lookup or something
similar.
</p>
        <p>
Notice that the method returns a PartialViewResult that uses the same user control
that I used to bootstrap the <em>thespan</em> element. This means that every time
the link is clicked, the GetNext method is updated, and the exact same user control
is used to render the content that dynamically replaces the original content of the
element.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=73a82937-3edf-4e01-ae35-273a93d68160" />
      </body>
      <title>Self-updating AJAX links with ASP.NET MVC</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</guid>
      <link>http://blog.ploeh.dk/2009/09/07/SelfupdatingAJAXLinksWithASPNETMVC.aspx</link>
      <pubDate>Mon, 07 Sep 2009 18:14:39 GMT</pubDate>
      <description>&lt;p&gt;
How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel
and I recently had that problem and we couldn't find any guidance on this topic, so
now that we have a solution, I thought I'd share it.
&lt;/p&gt;
&lt;p&gt;
The problem is simple: We needed a link that invoked some server side code and updated
the text of the link itself based on the result of the operation. Here is a simplified
example:
&lt;/p&gt;
&lt;p&gt;
&lt;a href="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_2.png"&gt;&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/SelfupdatingAJAXlinkswithASP.NETMVC_791E/image_thumb.png" width="267" height="75"&gt;&lt;/a&gt; 
&lt;/p&gt;
&lt;p&gt;
Each time you click the link, it should invoke a Controller Action and return a new
number that should appear as the link text.
&lt;/p&gt;
&lt;p&gt;
This is pretty simple to implement once you know how. The first thing to realize is
that the link and all the AJAX stuff must be placed in a user control. The only thing
that needs to go into the containing page is the containing element itself:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &amp;lt;\cf3 h2\cf1 &amp;gt;\cf0 Self-updating AJAX link\cf1 &amp;lt;/\cf3 h2\cf1 &amp;gt;\par ??\cf0 Click the link to update the number:\par ??\cf1 &amp;lt;\cf3 span\cf0  \cf5 id\cf1 ="thespan"&amp;gt;\par ??\cf0     \cb6\highlight6 &amp;lt;%\cb0\highlight0  \cf1 this\cf0 .Html.RenderPartial(\cf3 "NumberAjaxUserControl"\cf0 ); \cb6\highlight6 %&amp;gt;\par ??\cf1\cb0\highlight0 &amp;lt;/\cf3 span\cf1 &amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;h2&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;Self-updating
AJAX link&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;h2&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;Click the link to update the number:&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;span&lt;/span&gt; &lt;span style="color: red"&gt;id&lt;/span&gt;&lt;span style="color: blue"&gt;="thespan"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Html.RenderPartial(&lt;span style="color: #a31515"&gt;"NumberAjaxUserControl"&lt;/span&gt;); &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;span&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice the &lt;em&gt;id&lt;/em&gt; of the span element – this same &lt;em&gt;id&lt;/em&gt; will be referenced
from the user control.
&lt;/p&gt;
&lt;p&gt;
To bootstrap this view, the Controller Action for the page contains code that assigns
an initial value to the number (in this case &lt;em&gt;1&lt;/em&gt;):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 ActionResult\cf0  Index()\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = 1.ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .View();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ActionResult&lt;/span&gt; Index()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;]
= 1.ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.View();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
To keep the example simple, I simply add the number to the ViewData dictionary, but
in any production implementation, I would opt to use a strongly typed ViewModel instead.
&lt;/p&gt;
&lt;p&gt;
The NumberAjaxUserControl itself only contains the definition of the AJAX link:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red43\green145\blue175;}??\fs20 \cb2\highlight2 &amp;lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Control\cf0  \cf6 Language\cf3 ="C#"\cf0  \cf6 Inherits\cf3 ="System.Web.Mvc.ViewUserControl"\cf0  \cb2\highlight2 %&amp;gt;\par ??&amp;lt;%\cf3\cb0\highlight0 @\cf0  \cf5 Import\cf0  \cf6 Namespace\cf3 ="System.Web.Mvc.Ajax"\cf0  \cb2\highlight2 %&amp;gt;\par ??&amp;lt;%\cf3\cb0\highlight0 =\cf0  \cf3 this\cf0 .Ajax.ActionLink((\cf3 string\cf0 )\cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ],\par ??    \cf5 "GetNext"\cf0 ,\par ??    \cf3 new\cf0  \{ number = \cf3 this\cf0 .ViewData[\cf5 "number"\cf0 ] \}, \par ??    \cf3 new\cf0  \cf7 AjaxOptions\cf0  \{ UpdateTargetId = \cf5 "thespan"\cf0  \})\cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;@&lt;/span&gt; &lt;span style="color: #a31515"&gt;Control&lt;/span&gt; &lt;span style="color: red"&gt;Language&lt;/span&gt;&lt;span style="color: blue"&gt;="C#"&lt;/span&gt; &lt;span style="color: red"&gt;Inherits&lt;/span&gt;&lt;span style="color: blue"&gt;="System.Web.Mvc.ViewUserControl"&lt;/span&gt; &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;@&lt;/span&gt; &lt;span style="color: #a31515"&gt;Import&lt;/span&gt; &lt;span style="color: red"&gt;Namespace&lt;/span&gt;&lt;span style="color: blue"&gt;="System.Web.Mvc.Ajax"&lt;/span&gt; &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Ajax.ActionLink((&lt;span style="color: blue"&gt;string&lt;/span&gt;)&lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;],&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"GetNext"&lt;/span&gt;,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; {
number = &lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;]
}, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;AjaxOptions&lt;/span&gt; {
UpdateTargetId = &lt;span style="color: #a31515"&gt;"thespan"&lt;/span&gt; })&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The first parameter to the ActionLink method is simply the current number to render
as the link text. Since I'm using the untyped ViewData dictionary for this example,
I need to cast it to a string.
&lt;/p&gt;
&lt;p&gt;
The next parameter ("GetNext") indicates the Controller Action to invoke when the
link is clicked – I will cover that shortly.
&lt;/p&gt;
&lt;p&gt;
The third parameter is a Route Value that specifies that the parameter &lt;em&gt;number&lt;/em&gt; with
the correct value will be supplied to the GetNext Controller Action. It uses the number
stored in ViewData.
&lt;/p&gt;
&lt;p&gt;
The last parameter indicates the &lt;em&gt;id&lt;/em&gt; of the element to update. Recall from
before that this name was "thespan".
&lt;/p&gt;
&lt;p&gt;
The only missing piece now is the GetNext Controller Action:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf4 PartialViewResult\cf0  GetNext(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 this\cf0 .ViewData[\cf5 "number"\cf0 ] = (number + 1).ToString();\par ??    \cf1 return\cf0  \cf1 this\cf0 .PartialView(\cf5 "NumberAjaxUserControl"\cf0 );\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PartialViewResult&lt;/span&gt; GetNext(&lt;span style="color: blue"&gt;int&lt;/span&gt; number)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ViewData[&lt;span style="color: #a31515"&gt;"number"&lt;/span&gt;]
= (number + 1).ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.PartialView(&lt;span style="color: #a31515"&gt;"NumberAjaxUserControl"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this example I simply chose to increment the number by one, but I'm sure you can
imagine that this method could just as well perform a database lookup or something
similar.
&lt;/p&gt;
&lt;p&gt;
Notice that the method returns a PartialViewResult that uses the same user control
that I used to bootstrap the &lt;em&gt;thespan&lt;/em&gt; element. This means that every time
the link is clicked, the GetNext method is updated, and the exact same user control
is used to render the content that dynamically replaces the original content of the
element.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=73a82937-3edf-4e01-ae35-273a93d68160" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,73a82937-3edf-4e01-ae35-273a93d68160.aspx</comments>
      <category>ASP.NET MVC</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=146f7340-2e70-44ad-9b74-35e86432d2c7</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,146f7340-2e70-44ad-9b74-35e86432d2c7.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,146f7340-2e70-44ad-9b74-35e86432d2c7.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=146f7340-2e70-44ad-9b74-35e86432d2c7</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It gives me great pleasure to announce that I have just release version .8.5 of <a href="http://autofixture.codeplex.com/">AutoFixture</a>.
It is a minor release (hence the numbering) that mainly contains a lot of convenience
overloads to already existing methods. There is also a single bug fix.
</p>
        <p>
There are two breaking changes (documented on the <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31587">release
page</a>), but they are minor and I do not expect them to cause problems. Only one
of these even remotely affects any part of the API I have already discussed here,
and that relates to what kind of exception is being thrown <a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx">when
AutoFixture is unable to create an instance of the requested type</a>.
</p>
        <p>
Please go ahead and download it and use it heavily :) As always, comments and questions
are welcome.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=146f7340-2e70-44ad-9b74-35e86432d2c7" />
      </body>
      <title>AutoFixture .8.5 Released</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,146f7340-2e70-44ad-9b74-35e86432d2c7.aspx</guid>
      <link>http://blog.ploeh.dk/2009/09/02/AutoFixture85Released.aspx</link>
      <pubDate>Wed, 02 Sep 2009 20:21:13 GMT</pubDate>
      <description>&lt;p&gt;
It gives me great pleasure to announce that I have just release version .8.5 of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;.
It is a minor release (hence the numbering) that mainly contains a lot of convenience
overloads to already existing methods. There is also a single bug fix.
&lt;/p&gt;
&lt;p&gt;
There are two breaking changes (documented on the &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=31587"&gt;release
page&lt;/a&gt;), but they are minor and I do not expect them to cause problems. Only one
of these even remotely affects any part of the API I have already discussed here,
and that relates to what kind of exception is being thrown &lt;a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx"&gt;when
AutoFixture is unable to create an instance of the requested type&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Please go ahead and download it and use it heavily :) As always, comments and questions
are welcome.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=146f7340-2e70-44ad-9b74-35e86432d2c7" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,146f7340-2e70-44ad-9b74-35e86432d2c7.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=292e8e24-b3ae-4805-94c0-9511f23a6ec4</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,292e8e24-b3ae-4805-94c0-9511f23a6ec4.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,292e8e24-b3ae-4805-94c0-9511f23a6ec4.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=292e8e24-b3ae-4805-94c0-9511f23a6ec4</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Soon after I posted <a href="http://blog.ploeh.dk/2009/06/09/CallingMethodsWhileBuildingAnonymousVariablesWithAutoFixture.aspx">my
post on the AutoFixture Custom Builder's Do method</a>, a much better example occurred
to me, so let's revisit this feature in light of a more reasonable context.
</p>
        <p>
When I write WPF code, I always use the <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">MVVM
pattern</a>. When I need to create a Master/Detail View, I usually model it so that
my View Model has a list of available items, and a property that returns the currently
selected item. In this way, I can bind the current Detail View to the currently selected
item purely through the View Model.
</p>
        <p>
Such a View Model might look like this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 MyViewModel\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 List\cf0 &lt;\cf4 MyClass\cf0 &gt; availableItems;\par ??    \cf1 private\cf0  \cf4 MyClass\cf0  selectedItem;\par ??\par ??    \cf1 public\cf0  MyViewModel()\par ??    \{\par ??        \cf1 this\cf0 .availableItems = \cf1 new\cf0  \cf4 List\cf0 &lt;\cf4 MyClass\cf0 &gt;();\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf4 ICollection\cf0 &lt;\cf4 MyClass\cf0 &gt; AvailableItems\par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .availableItems; \}\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf4 MyClass\cf0  SelectedItem\par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .selectedItem; \}\par ??        \cf1 set\cf0  \par ??        \{\par ??            \cf1 if\cf0  (!\cf1 this\cf0 .availableItems.Contains(\cf1 value\cf0 ))\par ??            \{\par ??                \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentException\cf0 (\cf5 "..."\cf0 );\par ??            \}\par ??            \cf1 this\cf0 .selectedItem = \cf1 value\cf0 ;\par ??        \}\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">MyViewModel</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">MyClass</span>&gt;
availableItems;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: #2b91af">MyClass</span> selectedItem;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> MyViewModel()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.availableItems
= <span style="color: blue">new</span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">ICollection</span>&lt;<span style="color: #2b91af">MyClass</span>&gt;
AvailableItems</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">get</span> { <span style="color: blue">return</span><span style="color: blue">this</span>.availableItems;
}</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">MyClass</span> SelectedItem</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">get</span> { <span style="color: blue">return</span><span style="color: blue">this</span>.selectedItem;
}</pre>
          <pre style="margin: 0px">        <span style="color: blue">set</span></pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">if</span> (!<span style="color: blue">this</span>.availableItems.Contains(<span style="color: blue">value</span>))</pre>
          <pre style="margin: 0px">            {</pre>
          <pre style="margin: 0px">                <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">"..."</span>);</pre>
          <pre style="margin: 0px">            }</pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.selectedItem
= <span style="color: blue">value</span>;</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The main point of interest is that if you attempt to set SelectedItem to an instance
that's not contained in the list of available items, an exception will be thrown.
That's reasonable behavior, since we want the user to select only from the available
items.
</p>
        <p>
By default, <a href="http://autofixture.codeplex.com/">AutoFixture</a> works by assigning
an Anonymous Value to all writable properties. Since these values are auto-generated,
the value AutoFixture is going to assign to SelectedItem will be a new instance of
MyClass, and thus not one of the available items. In other words, this will throw
an exception:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.CreateAnonymous&lt;\cf4 MyViewModel\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mvm
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyViewModel</span>&gt;();</pre>
        </div>
        <p>
There are several solutions to this situation, depending on the scenario. If you need
an instance with SelectedItem correctly set to a non-null value, you can use the Do
method like this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClass\cf0 &gt;();\par ??\cf1 var\cf0  mvm = fixture.Build&lt;\cf4 MyViewModel\cf0 &gt;()\par ??    .Do(x =&gt; x.AvailableItems.Add(mc))\par ??    .With(x =&gt; x.SelectedItem, mc)\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mvm
= fixture.Build&lt;<span style="color: #2b91af">MyViewModel</span>&gt;()</pre>
          <pre style="margin: 0px">    .Do(x =&gt; x.AvailableItems.Add(mc))</pre>
          <pre style="margin: 0px">    .With(x =&gt; x.SelectedItem, mc)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
This first creates an anonymous instance of MyClass, adds it to AvailableItems as
part of a customized Builder pipeline and subsequently assigns it to SelectedItem.
</p>
        <p>
Another option is to skip assigning only the SelectedItem property. This is a good
option if you don't need that value in a particular test. You can use the <a href="http://blog.ploeh.dk/2009/08/17/OmittingOnlyCertainPropertiesWithAutoFixture.aspx">Without</a> method
to do that:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.Build&lt;\cf4 MyViewModel\cf0 &gt;()\par ??    .Without(s =&gt; s.SelectedItem)\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mvm
= fixture.Build&lt;<span style="color: #2b91af">MyViewModel</span>&gt;()</pre>
          <pre style="margin: 0px">    .Without(s =&gt; s.SelectedItem)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
This will assign a value to all other writable properties of MyViewModel (if it had
had any), except the SelectedItem property. In this case, the value of SelectedItem
will be null, since it is being ignored.
</p>
        <p>
Finally you can simply choose to omit all AutoProperties using the <a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx">OmitAutoProperties</a> method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.Build&lt;\cf4 MyViewModel\cf0 &gt;()\par ??    .OmitAutoProperties()\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mvm
= fixture.Build&lt;<span style="color: #2b91af">MyViewModel</span>&gt;()</pre>
          <pre style="margin: 0px">    .OmitAutoProperties()</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
In this scenario, only MyViewModel's constructor is being executed, while all writable
properties are being ignored.
</p>
        <p>
As you can see, AutoFixture offers great flexibility in providing specialized custom
Builders that fit almost any situation.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=292e8e24-b3ae-4805-94c0-9511f23a6ec4" />
      </body>
      <title>Do Redux</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,292e8e24-b3ae-4805-94c0-9511f23a6ec4.aspx</guid>
      <link>http://blog.ploeh.dk/2009/08/25/DoRedux.aspx</link>
      <pubDate>Tue, 25 Aug 2009 18:27:39 GMT</pubDate>
      <description>&lt;p&gt;
Soon after I posted &lt;a href="http://blog.ploeh.dk/2009/06/09/CallingMethodsWhileBuildingAnonymousVariablesWithAutoFixture.aspx"&gt;my
post on the AutoFixture Custom Builder's Do method&lt;/a&gt;, a much better example occurred
to me, so let's revisit this feature in light of a more reasonable context.
&lt;/p&gt;
&lt;p&gt;
When I write WPF code, I always use the &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;MVVM
pattern&lt;/a&gt;. When I need to create a Master/Detail View, I usually model it so that
my View Model has a list of available items, and a property that returns the currently
selected item. In this way, I can bind the current Detail View to the currently selected
item purely through the View Model.
&lt;/p&gt;
&lt;p&gt;
Such a View Model might look like this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 MyViewModel\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 List\cf0 &amp;lt;\cf4 MyClass\cf0 &amp;gt; availableItems;\par ??    \cf1 private\cf0  \cf4 MyClass\cf0  selectedItem;\par ??\par ??    \cf1 public\cf0  MyViewModel()\par ??    \{\par ??        \cf1 this\cf0 .availableItems = \cf1 new\cf0  \cf4 List\cf0 &amp;lt;\cf4 MyClass\cf0 &amp;gt;();\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf4 ICollection\cf0 &amp;lt;\cf4 MyClass\cf0 &amp;gt; AvailableItems\par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .availableItems; \}\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf4 MyClass\cf0  SelectedItem\par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .selectedItem; \}\par ??        \cf1 set\cf0  \par ??        \{\par ??            \cf1 if\cf0  (!\cf1 this\cf0 .availableItems.Contains(\cf1 value\cf0 ))\par ??            \{\par ??                \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentException\cf0 (\cf5 "..."\cf0 );\par ??            \}\par ??            \cf1 this\cf0 .selectedItem = \cf1 value\cf0 ;\par ??        \}\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;
availableItems;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt; selectedItem;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; MyViewModel()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.availableItems
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ICollection&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;
AvailableItems&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.availableItems;
}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt; SelectedItem&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.selectedItem;
}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;set&lt;/span&gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (!&lt;span style="color: blue"&gt;this&lt;/span&gt;.availableItems.Contains(&lt;span style="color: blue"&gt;value&lt;/span&gt;))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"..."&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.selectedItem
= &lt;span style="color: blue"&gt;value&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The main point of interest is that if you attempt to set SelectedItem to an instance
that's not contained in the list of available items, an exception will be thrown.
That's reasonable behavior, since we want the user to select only from the available
items.
&lt;/p&gt;
&lt;p&gt;
By default, &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; works by assigning
an Anonymous Value to all writable properties. Since these values are auto-generated,
the value AutoFixture is going to assign to SelectedItem will be a new instance of
MyClass, and thus not one of the available items. In other words, this will throw
an exception:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.CreateAnonymous&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mvm
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
There are several solutions to this situation, depending on the scenario. If you need
an instance with SelectedItem correctly set to a non-null value, you can use the Do
method like this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClass\cf0 &amp;gt;();\par ??\cf1 var\cf0  mvm = fixture.Build&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;()\par ??    .Do(x =&amp;gt; x.AvailableItems.Add(mc))\par ??    .With(x =&amp;gt; x.SelectedItem, mc)\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mvm
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Do(x =&amp;gt; x.AvailableItems.Add(mc))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(x =&amp;gt; x.SelectedItem, mc)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This first creates an anonymous instance of MyClass, adds it to AvailableItems as
part of a customized Builder pipeline and subsequently assigns it to SelectedItem.
&lt;/p&gt;
&lt;p&gt;
Another option is to skip assigning only the SelectedItem property. This is a good
option if you don't need that value in a particular test. You can use the &lt;a href="http://blog.ploeh.dk/2009/08/17/OmittingOnlyCertainPropertiesWithAutoFixture.aspx"&gt;Without&lt;/a&gt; method
to do that:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.Build&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;()\par ??    .Without(s =&amp;gt; s.SelectedItem)\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mvm
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Without(s =&amp;gt; s.SelectedItem)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This will assign a value to all other writable properties of MyViewModel (if it had
had any), except the SelectedItem property. In this case, the value of SelectedItem
will be null, since it is being ignored.
&lt;/p&gt;
&lt;p&gt;
Finally you can simply choose to omit all AutoProperties using the &lt;a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx"&gt;OmitAutoProperties&lt;/a&gt; method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mvm = fixture.Build&amp;lt;\cf4 MyViewModel\cf0 &amp;gt;()\par ??    .OmitAutoProperties()\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mvm
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyViewModel&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .OmitAutoProperties()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this scenario, only MyViewModel's constructor is being executed, while all writable
properties are being ignored.
&lt;/p&gt;
&lt;p&gt;
As you can see, AutoFixture offers great flexibility in providing specialized custom
Builders that fit almost any situation.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=292e8e24-b3ae-4805-94c0-9511f23a6ec4" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,292e8e24-b3ae-4805-94c0-9511f23a6ec4.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=0fd21249-f8d1-4095-b428-42db301f63cc</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,0fd21249-f8d1-4095-b428-42db301f63cc.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,0fd21249-f8d1-4095-b428-42db301f63cc.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=0fd21249-f8d1-4095-b428-42db301f63cc</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The default behavior of <a href="http://autofixture.codeplex.com/">AutoFixture</a> is
to create an Anonymous Variable by assigning a value to all writable properties of
the created instance. This is great in many scenarios, but not so much in others.
You can <a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx">disable
this behavior by using the OmitAutoProperties method</a>, but sometimes, you <em>would</em> like
most of the writable properties set, except one or two.
</p>
        <p>
Consider this simple Person class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 Person\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf4 Person\cf0  spouse;\par ??\par ??    \cf1 public\cf0  \cf4 DateTime\cf0  BirthDay \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\par ??    \cf1 public\cf0  \cf1 string\cf0  Name \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\par ??    \cf1 public\cf0  \cf4 Person\cf0  Spouse \par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .spouse; \}\par ??        \cf1 set\par ??\cf0         \{\par ??            \cf1 this\cf0 .spouse = \cf1 value\cf0 ;\par ??            \cf1 if\cf0  (\cf1 value\cf0  != \cf1 null\cf0 )\par ??            \{\par ??                \cf1 value\cf0 .spouse = \cf1 this\cf0 ;\par ??            \}\par ??        \}\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Person</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: #2b91af">Person</span> spouse;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">DateTime</span> BirthDay
{ <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">string</span> Name
{ <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">Person</span> Spouse </pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">get</span> { <span style="color: blue">return</span><span style="color: blue">this</span>.spouse;
}</pre>
          <pre style="margin: 0px">        <span style="color: blue">set</span></pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.spouse
= <span style="color: blue">value</span>;</pre>
          <pre style="margin: 0px">            <span style="color: blue">if</span> (<span style="color: blue">value</span> != <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">            {</pre>
          <pre style="margin: 0px">                <span style="color: blue">value</span>.spouse
= <span style="color: blue">this</span>;</pre>
          <pre style="margin: 0px">            }</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The main trouble with this class, seen from AutoFixture's perspective, is the circular
reference exposed by the Spouse property. When AutoFixture attempts to create an anonymous
instance of Person, it will create anonymous values for all writable properties, and
that includes the Spouse property, so it attempts to create a new instance of the
Person class and assign values to all public properties, including the Spouse property,
etc.
</p>
        <p>
In other words, this line of code throws a StackOverflowException:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  person = fixture.CreateAnonymous&lt;\cf4 Person\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> person
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Person</span>&gt;();</pre>
        </div>
        <p>
If you would still like to have anonymous values assigned to Name and BirthDay, you
can use the Without method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  person = fixture.Build&lt;\cf4 Person\cf0 &gt;()\par ??    .Without(p =&gt; p.Spouse)\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> person
= fixture.Build&lt;<span style="color: #2b91af">Person</span>&gt;()</pre>
          <pre style="margin: 0px">    .Without(p =&gt; p.Spouse)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
This will give you an anonymous instance of the Person class, but with the Spouse
property still with its default value of null.
</p>
        <p>
Several calls to Without can be chained if you want to skip more than one property.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0fd21249-f8d1-4095-b428-42db301f63cc" />
      </body>
      <title>Omitting Only Certain Properties With AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,0fd21249-f8d1-4095-b428-42db301f63cc.aspx</guid>
      <link>http://blog.ploeh.dk/2009/08/17/OmittingOnlyCertainPropertiesWithAutoFixture.aspx</link>
      <pubDate>Mon, 17 Aug 2009 19:33:40 GMT</pubDate>
      <description>&lt;p&gt;
The default behavior of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; is
to create an Anonymous Variable by assigning a value to all writable properties of
the created instance. This is great in many scenarios, but not so much in others.
You can &lt;a href="http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx"&gt;disable
this behavior by using the OmitAutoProperties method&lt;/a&gt;, but sometimes, you &lt;em&gt;would&lt;/em&gt; like
most of the writable properties set, except one or two.
&lt;/p&gt;
&lt;p&gt;
Consider this simple Person class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 Person\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf4 Person\cf0  spouse;\par ??\par ??    \cf1 public\cf0  \cf4 DateTime\cf0  BirthDay \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\par ??    \cf1 public\cf0  \cf1 string\cf0  Name \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\par ??    \cf1 public\cf0  \cf4 Person\cf0  Spouse \par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .spouse; \}\par ??        \cf1 set\par ??\cf0         \{\par ??            \cf1 this\cf0 .spouse = \cf1 value\cf0 ;\par ??            \cf1 if\cf0  (\cf1 value\cf0  != \cf1 null\cf0 )\par ??            \{\par ??                \cf1 value\cf0 .spouse = \cf1 this\cf0 ;\par ??            \}\par ??        \}\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Person&lt;/span&gt; spouse;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt; BirthDay
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; Name
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Person&lt;/span&gt; Spouse &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.spouse;
}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;set&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.spouse
= &lt;span style="color: blue"&gt;value&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (&lt;span style="color: blue"&gt;value&lt;/span&gt; != &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;value&lt;/span&gt;.spouse
= &lt;span style="color: blue"&gt;this&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The main trouble with this class, seen from AutoFixture's perspective, is the circular
reference exposed by the Spouse property. When AutoFixture attempts to create an anonymous
instance of Person, it will create anonymous values for all writable properties, and
that includes the Spouse property, so it attempts to create a new instance of the
Person class and assign values to all public properties, including the Spouse property,
etc.
&lt;/p&gt;
&lt;p&gt;
In other words, this line of code throws a StackOverflowException:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  person = fixture.CreateAnonymous&amp;lt;\cf4 Person\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; person
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
If you would still like to have anonymous values assigned to Name and BirthDay, you
can use the Without method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  person = fixture.Build&amp;lt;\cf4 Person\cf0 &amp;gt;()\par ??    .Without(p =&amp;gt; p.Spouse)\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; person
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Without(p =&amp;gt; p.Spouse)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This will give you an anonymous instance of the Person class, but with the Spouse
property still with its default value of null.
&lt;/p&gt;
&lt;p&gt;
Several calls to Without can be chained if you want to skip more than one property.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0fd21249-f8d1-4095-b428-42db301f63cc" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,0fd21249-f8d1-4095-b428-42db301f63cc.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=be02d84b-712f-4d40-ad4f-66e34bed4fc9</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,be02d84b-712f-4d40-ad4f-66e34bed4fc9.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,be02d84b-712f-4d40-ad4f-66e34bed4fc9.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=be02d84b-712f-4d40-ad4f-66e34bed4fc9</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
If you are doing Rich UI, <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx">INotifyPropertyChanged</a> is
a pretty important interface. This is as true for WPF as it was for Windows Forms.
Consisting solely of an event, it's <a href="http://blogs.msdn.com/ploeh/archive/2006/01/19/TestingEventsUsingAnonymousMethods.aspx">not
any harder to unit test than other events</a>.
</p>
        <p>
You can certainly write each test manually like the following.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ChangingMyPropertyWillRaiseNotifyEvent_Classic()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 bool\cf0  eventWasRaised = \cf4 false\cf0 ;\par ??    \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 ();\par ??    sut.PropertyChanged += (sender, e) =&gt;\par ??        \{\par ??            \cf4 if\cf0  (e.PropertyName == \cf6 "MyProperty"\cf0 )\par ??            \{\par ??                eventWasRaised = \cf4 true\cf0 ;\par ??            \}\par ??        \};\par ??    \cf5 // Exercise system\par ??\cf0     sut.MyProperty = \cf6 "Some new value"\cf0 ;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .IsTrue(eventWasRaised, \cf6 "Event was raised"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ChangingMyPropertyWillRaiseNotifyEvent_Classic()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">bool</span> eventWasRaised
= <span style="color: blue">false</span>;</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>();</pre>
          <pre style="margin: 0px">    sut.PropertyChanged += (sender, e) =&gt;</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">if</span> (e.PropertyName
== <span style="color: #a31515">"MyProperty"</span>)</pre>
          <pre style="margin: 0px">            {</pre>
          <pre style="margin: 0px">                eventWasRaised = <span style="color: blue">true</span>;</pre>
          <pre style="margin: 0px">            }</pre>
          <pre style="margin: 0px">        };</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.MyProperty = <span style="color: #a31515">"Some
new value"</span>;</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.IsTrue(eventWasRaised, <span style="color: #a31515">"Event
was raised"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Even for a one-off test, this one has a few problems. From an <a href="http://xunitpatterns.com/"><em>xUnit
Test Patterns</em></a> point of view, there's the issue that the test contains conditional
logic, but that aside, the main problem is that if you have a lot of properties, writing
all these very similar tests become old hat very soon.
</p>
        <p>
To make testing INotifyPropertyChanged events easier, I created a simple fluent interface
that allows me to write the same test like this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ChangingMyPropertyWillRaiseNotifyEvent_Fluent()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 ();\par ??    \cf5 // Exercise system and verify outcome\par ??\cf0     sut.ShouldNotifyOn(s =&gt; s.MyProperty)\par ??        .When(s =&gt; s.MyProperty = \cf6 "Some new value"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ChangingMyPropertyWillRaiseNotifyEvent_Fluent()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system and verify outcome</span></pre>
          <pre style="margin: 0px">    sut.ShouldNotifyOn(s =&gt; s.MyProperty)</pre>
          <pre style="margin: 0px">        .When(s =&gt; s.MyProperty = <span style="color: #a31515">"Some
new value"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
You simply state for which property you want to verify the event when a certain operation
is invoked. This is certainly more concise and intention-revealing than the previous
test.
</p>
        <p>
If you have interdependent properties, you can specify than an event was raised when
another property was modified.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ChangingMyPropertyWillRaiseNotifyForDerived()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 ();\par ??    \cf5 // Exercise system and verify outcome\par ??\cf0     sut.ShouldNotifyOn(s =&gt; s.MyDerivedProperty)\par ??        .When(s =&gt; s.MyProperty = \cf6 "Some new value"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ChangingMyPropertyWillRaiseNotifyForDerived()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system and verify outcome</span></pre>
          <pre style="margin: 0px">    sut.ShouldNotifyOn(s =&gt; s.MyDerivedProperty)</pre>
          <pre style="margin: 0px">        .When(s =&gt; s.MyProperty = <span style="color: #a31515">"Some
new value"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The When method takes any Action&lt;T&gt;, so you can also invoke methods, use Closures
and what not.
</p>
        <p>
There's also a <em>ShouldNotNotifyOn</em> method to verify that an event was <em>not</em> raised
when a particular operation was invoked.
</p>
        <p>
This fluent interface is implemented with an extension method on INotifyPropertyChanged,
combined with a custom class that performs the verification. Here are the extension
methods:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf4 NotifyPropertyChanged\par ??\cf0 \{\par ??    \cf1 public\cf0  \cf1 static\cf0  \cf4 NotifyExpectation\cf0 &lt;T&gt;\par ??        ShouldNotifyOn&lt;T, TProperty&gt;(\cf1 this\cf0  T owner,\par ??        \cf4 Expression\cf0 &lt;\cf4 Func\cf0 &lt;T, TProperty&gt;&gt; propertyPicker) \par ??        \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0     \{\par ??        \cf1 return\cf0  \cf4 NotifyPropertyChanged\cf0 .CreateExpectation(owner,\par ??            propertyPicker, \cf1 true\cf0 );\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 static\cf0  \cf4 NotifyExpectation\cf0 &lt;T&gt; \par ??        ShouldNotNotifyOn&lt;T, TProperty&gt;(\cf1 this\cf0  T owner,\par ??        \cf4 Expression\cf0 &lt;\cf4 Func\cf0 &lt;T, TProperty&gt;&gt; propertyPicker)\par ??        \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0     \{\par ??        \cf1 return\cf0  \cf4 NotifyPropertyChanged\cf0 .CreateExpectation(owner,\par ??            propertyPicker, \cf1 false\cf0 );\par ??    \}\par ??\par ??    \cf1 private\cf0  \cf1 static\cf0  \cf4 NotifyExpectation\cf0 &lt;T&gt;\par ??        CreateExpectation&lt;T, TProperty&gt;(T owner,\par ??        \cf4 Expression\cf0 &lt;\cf4 Func\cf0 &lt;T, TProperty&gt;&gt; pickProperty,\par ??        \cf1 bool\cf0  eventExpected) \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0     \{\par ??        \cf1 string\cf0  propertyName =\par ??            ((\cf4 MemberExpression\cf0 )pickProperty.Body).Member.Name;\par ??        \cf1 return\cf0  \cf1 new\cf0  \cf4 NotifyExpectation\cf0 &lt;T&gt;(owner,\par ??            propertyName, eventExpected);\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">static</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">NotifyPropertyChanged</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: #2b91af">NotifyExpectation</span>&lt;T&gt;</pre>
          <pre style="margin: 0px">        ShouldNotifyOn&lt;T, TProperty&gt;(<span style="color: blue">this</span> T
owner,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T,
TProperty&gt;&gt; propertyPicker) </pre>
          <pre style="margin: 0px">        <span style="color: blue">where</span> T
: <span style="color: #2b91af">INotifyPropertyChanged</span></pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: #2b91af">NotifyPropertyChanged</span>.CreateExpectation(owner,</pre>
          <pre style="margin: 0px">            propertyPicker, <span style="color: blue">true</span>);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: #2b91af">NotifyExpectation</span>&lt;T&gt; </pre>
          <pre style="margin: 0px">        ShouldNotNotifyOn&lt;T, TProperty&gt;(<span style="color: blue">this</span> T
owner,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T,
TProperty&gt;&gt; propertyPicker)</pre>
          <pre style="margin: 0px">        <span style="color: blue">where</span> T
: <span style="color: #2b91af">INotifyPropertyChanged</span></pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: #2b91af">NotifyPropertyChanged</span>.CreateExpectation(owner,</pre>
          <pre style="margin: 0px">            propertyPicker, <span style="color: blue">false</span>);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">static</span><span style="color: #2b91af">NotifyExpectation</span>&lt;T&gt;</pre>
          <pre style="margin: 0px">        CreateExpectation&lt;T, TProperty&gt;(T owner,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Expression</span>&lt;<span style="color: #2b91af">Func</span>&lt;T,
TProperty&gt;&gt; pickProperty,</pre>
          <pre style="margin: 0px">        <span style="color: blue">bool</span> eventExpected) <span style="color: blue">where</span> T
: <span style="color: #2b91af">INotifyPropertyChanged</span></pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">string</span> propertyName
=</pre>
          <pre style="margin: 0px">            ((<span style="color: #2b91af">MemberExpression</span>)pickProperty.Body).Member.Name;</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">NotifyExpectation</span>&lt;T&gt;(owner,</pre>
          <pre style="margin: 0px">            propertyName, eventExpected);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
And here's the NotifyExpectation class returned by both extension methods:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 NotifyExpectation\cf0 &lt;T&gt;\par ??    \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  T owner;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 string\cf0  propertyName;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 bool\cf0  eventExpected;\par ??\par ??    \cf1 public\cf0  NotifyExpectation(T owner,\par ??        \cf1 string\cf0  propertyName, \cf1 bool\cf0  eventExpected)\par ??    \{\par ??        \cf1 this\cf0 .owner = owner;\par ??        \cf1 this\cf0 .propertyName = propertyName;\par ??        \cf1 this\cf0 .eventExpected = eventExpected;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  When(\cf4 Action\cf0 &lt;T&gt; action)\par ??    \{\par ??        \cf1 bool\cf0  eventWasRaised = \cf1 false\cf0 ;\par ??        \cf1 this\cf0 .owner.PropertyChanged += (sender, e) =&gt;\par ??        \{\par ??            \cf1 if\cf0  (e.PropertyName == \cf1 this\cf0 .propertyName)\par ??            \{\par ??                eventWasRaised = \cf1 true\cf0 ;\par ??            \}\par ??        \};\par ??        action(\cf1 this\cf0 .owner);\par ??\par ??        \cf4 Assert\cf0 .AreEqual&lt;\cf1 bool\cf0 &gt;(\cf1 this\cf0 .eventExpected,\par ??            eventWasRaised,\par ??            \cf5 "PropertyChanged on \{0\}"\cf0 , \cf1 this\cf0 .propertyName);\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">NotifyExpectation</span>&lt;T&gt;</pre>
          <pre style="margin: 0px">    <span style="color: blue">where</span> T
: <span style="color: #2b91af">INotifyPropertyChanged</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span> T
owner;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">string</span> propertyName;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">bool</span> eventExpected;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> NotifyExpectation(T
owner,</pre>
          <pre style="margin: 0px">        <span style="color: blue">string</span> propertyName, <span style="color: blue">bool</span> eventExpected)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.owner
= owner;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.propertyName
= propertyName;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.eventExpected
= eventExpected;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> When(<span style="color: #2b91af">Action</span>&lt;T&gt;
action)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">bool</span> eventWasRaised
= <span style="color: blue">false</span>;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.owner.PropertyChanged
+= (sender, e) =&gt;</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">if</span> (e.PropertyName
== <span style="color: blue">this</span>.propertyName)</pre>
          <pre style="margin: 0px">            {</pre>
          <pre style="margin: 0px">                eventWasRaised = <span style="color: blue">true</span>;</pre>
          <pre style="margin: 0px">            }</pre>
          <pre style="margin: 0px">        };</pre>
          <pre style="margin: 0px">        action(<span style="color: blue">this</span>.owner);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Assert</span>.AreEqual&lt;<span style="color: blue">bool</span>&gt;(<span style="color: blue">this</span>.eventExpected,</pre>
          <pre style="margin: 0px">            eventWasRaised,</pre>
          <pre style="margin: 0px">            <span style="color: #a31515">"PropertyChanged
on {0}"</span>, <span style="color: blue">this</span>.propertyName);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
You can replace the Assertion with one that matches your test framework of choice
(this one was written for MSTest).
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be02d84b-712f-4d40-ad4f-66e34bed4fc9" />
      </body>
      <title>A Fluent Interface For Testing INotifyPropertyChanged</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,be02d84b-712f-4d40-ad4f-66e34bed4fc9.aspx</guid>
      <link>http://blog.ploeh.dk/2009/08/06/AFluentInterfaceForTestingINotifyPropertyChanged.aspx</link>
      <pubDate>Thu, 06 Aug 2009 17:58:36 GMT</pubDate>
      <description>&lt;p&gt;
If you are doing Rich UI, &lt;a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx"&gt;INotifyPropertyChanged&lt;/a&gt; is
a pretty important interface. This is as true for WPF as it was for Windows Forms.
Consisting solely of an event, it's &lt;a href="http://blogs.msdn.com/ploeh/archive/2006/01/19/TestingEventsUsingAnonymousMethods.aspx"&gt;not
any harder to unit test than other events&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
You can certainly write each test manually like the following.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ChangingMyPropertyWillRaiseNotifyEvent_Classic()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 bool\cf0  eventWasRaised = \cf4 false\cf0 ;\par ??    \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 ();\par ??    sut.PropertyChanged += (sender, e) =&amp;gt;\par ??        \{\par ??            \cf4 if\cf0  (e.PropertyName == \cf6 "MyProperty"\cf0 )\par ??            \{\par ??                eventWasRaised = \cf4 true\cf0 ;\par ??            \}\par ??        \};\par ??    \cf5 // Exercise system\par ??\cf0     sut.MyProperty = \cf6 "Some new value"\cf0 ;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .IsTrue(eventWasRaised, \cf6 "Event was raised"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ChangingMyPropertyWillRaiseNotifyEvent_Classic()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;bool&lt;/span&gt; eventWasRaised
= &lt;span style="color: blue"&gt;false&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.PropertyChanged += (sender, e) =&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (e.PropertyName
== &lt;span style="color: #a31515"&gt;"MyProperty"&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eventWasRaised = &lt;span style="color: blue"&gt;true&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.MyProperty = &lt;span style="color: #a31515"&gt;"Some
new value"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsTrue(eventWasRaised, &lt;span style="color: #a31515"&gt;"Event
was raised"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Even for a one-off test, this one has a few problems. From an &lt;a href="http://xunitpatterns.com/"&gt;&lt;em&gt;xUnit
Test Patterns&lt;/em&gt;&lt;/a&gt; point of view, there's the issue that the test contains conditional
logic, but that aside, the main problem is that if you have a lot of properties, writing
all these very similar tests become old hat very soon.
&lt;/p&gt;
&lt;p&gt;
To make testing INotifyPropertyChanged events easier, I created a simple fluent interface
that allows me to write the same test like this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ChangingMyPropertyWillRaiseNotifyEvent_Fluent()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 ();\par ??    \cf5 // Exercise system and verify outcome\par ??\cf0     sut.ShouldNotifyOn(s =&amp;gt; s.MyProperty)\par ??        .When(s =&amp;gt; s.MyProperty = \cf6 "Some new value"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ChangingMyPropertyWillRaiseNotifyEvent_Fluent()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system and verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.ShouldNotifyOn(s =&amp;gt; s.MyProperty)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .When(s =&amp;gt; s.MyProperty = &lt;span style="color: #a31515"&gt;"Some
new value"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
You simply state for which property you want to verify the event when a certain operation
is invoked. This is certainly more concise and intention-revealing than the previous
test.
&lt;/p&gt;
&lt;p&gt;
If you have interdependent properties, you can specify than an event was raised when
another property was modified.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ChangingMyPropertyWillRaiseNotifyForDerived()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 ();\par ??    \cf5 // Exercise system and verify outcome\par ??\cf0     sut.ShouldNotifyOn(s =&amp;gt; s.MyDerivedProperty)\par ??        .When(s =&amp;gt; s.MyProperty = \cf6 "Some new value"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ChangingMyPropertyWillRaiseNotifyForDerived()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system and verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; sut.ShouldNotifyOn(s =&amp;gt; s.MyDerivedProperty)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .When(s =&amp;gt; s.MyProperty = &lt;span style="color: #a31515"&gt;"Some
new value"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The When method takes any Action&amp;lt;T&amp;gt;, so you can also invoke methods, use Closures
and what not.
&lt;/p&gt;
&lt;p&gt;
There's also a &lt;em&gt;ShouldNotNotifyOn&lt;/em&gt; method to verify that an event was &lt;em&gt;not&lt;/em&gt; raised
when a particular operation was invoked.
&lt;/p&gt;
&lt;p&gt;
This fluent interface is implemented with an extension method on INotifyPropertyChanged,
combined with a custom class that performs the verification. Here are the extension
methods:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf4 NotifyPropertyChanged\par ??\cf0 \{\par ??    \cf1 public\cf0  \cf1 static\cf0  \cf4 NotifyExpectation\cf0 &amp;lt;T&amp;gt;\par ??        ShouldNotifyOn&amp;lt;T, TProperty&amp;gt;(\cf1 this\cf0  T owner,\par ??        \cf4 Expression\cf0 &amp;lt;\cf4 Func\cf0 &amp;lt;T, TProperty&amp;gt;&amp;gt; propertyPicker) \par ??        \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0     \{\par ??        \cf1 return\cf0  \cf4 NotifyPropertyChanged\cf0 .CreateExpectation(owner,\par ??            propertyPicker, \cf1 true\cf0 );\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 static\cf0  \cf4 NotifyExpectation\cf0 &amp;lt;T&amp;gt; \par ??        ShouldNotNotifyOn&amp;lt;T, TProperty&amp;gt;(\cf1 this\cf0  T owner,\par ??        \cf4 Expression\cf0 &amp;lt;\cf4 Func\cf0 &amp;lt;T, TProperty&amp;gt;&amp;gt; propertyPicker)\par ??        \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0     \{\par ??        \cf1 return\cf0  \cf4 NotifyPropertyChanged\cf0 .CreateExpectation(owner,\par ??            propertyPicker, \cf1 false\cf0 );\par ??    \}\par ??\par ??    \cf1 private\cf0  \cf1 static\cf0  \cf4 NotifyExpectation\cf0 &amp;lt;T&amp;gt;\par ??        CreateExpectation&amp;lt;T, TProperty&amp;gt;(T owner,\par ??        \cf4 Expression\cf0 &amp;lt;\cf4 Func\cf0 &amp;lt;T, TProperty&amp;gt;&amp;gt; pickProperty,\par ??        \cf1 bool\cf0  eventExpected) \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0     \{\par ??        \cf1 string\cf0  propertyName =\par ??            ((\cf4 MemberExpression\cf0 )pickProperty.Body).Member.Name;\par ??        \cf1 return\cf0  \cf1 new\cf0  \cf4 NotifyExpectation\cf0 &amp;lt;T&amp;gt;(owner,\par ??            propertyName, eventExpected);\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyPropertyChanged&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyExpectation&lt;/span&gt;&amp;lt;T&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ShouldNotifyOn&amp;lt;T, TProperty&amp;gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt; T
owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,
TProperty&amp;gt;&amp;gt; propertyPicker) &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;where&lt;/span&gt; T
: &lt;span style="color: #2b91af"&gt;INotifyPropertyChanged&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyPropertyChanged&lt;/span&gt;.CreateExpectation(owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; propertyPicker, &lt;span style="color: blue"&gt;true&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyExpectation&lt;/span&gt;&amp;lt;T&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ShouldNotNotifyOn&amp;lt;T, TProperty&amp;gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt; T
owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,
TProperty&amp;gt;&amp;gt; propertyPicker)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;where&lt;/span&gt; T
: &lt;span style="color: #2b91af"&gt;INotifyPropertyChanged&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyPropertyChanged&lt;/span&gt;.CreateExpectation(owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; propertyPicker, &lt;span style="color: blue"&gt;false&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyExpectation&lt;/span&gt;&amp;lt;T&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; CreateExpectation&amp;lt;T, TProperty&amp;gt;(T owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Expression&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T,
TProperty&amp;gt;&amp;gt; pickProperty,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;bool&lt;/span&gt; eventExpected) &lt;span style="color: blue"&gt;where&lt;/span&gt; T
: &lt;span style="color: #2b91af"&gt;INotifyPropertyChanged&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;string&lt;/span&gt; propertyName
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; ((&lt;span style="color: #2b91af"&gt;MemberExpression&lt;/span&gt;)pickProperty.Body).Member.Name;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyExpectation&lt;/span&gt;&amp;lt;T&amp;gt;(owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; propertyName, eventExpected);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
And here's the NotifyExpectation class returned by both extension methods:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 NotifyExpectation\cf0 &amp;lt;T&amp;gt;\par ??    \cf1 where\cf0  T : \cf4 INotifyPropertyChanged\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  T owner;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 string\cf0  propertyName;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 bool\cf0  eventExpected;\par ??\par ??    \cf1 public\cf0  NotifyExpectation(T owner,\par ??        \cf1 string\cf0  propertyName, \cf1 bool\cf0  eventExpected)\par ??    \{\par ??        \cf1 this\cf0 .owner = owner;\par ??        \cf1 this\cf0 .propertyName = propertyName;\par ??        \cf1 this\cf0 .eventExpected = eventExpected;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  When(\cf4 Action\cf0 &amp;lt;T&amp;gt; action)\par ??    \{\par ??        \cf1 bool\cf0  eventWasRaised = \cf1 false\cf0 ;\par ??        \cf1 this\cf0 .owner.PropertyChanged += (sender, e) =&amp;gt;\par ??        \{\par ??            \cf1 if\cf0  (e.PropertyName == \cf1 this\cf0 .propertyName)\par ??            \{\par ??                eventWasRaised = \cf1 true\cf0 ;\par ??            \}\par ??        \};\par ??        action(\cf1 this\cf0 .owner);\par ??\par ??        \cf4 Assert\cf0 .AreEqual&amp;lt;\cf1 bool\cf0 &amp;gt;(\cf1 this\cf0 .eventExpected,\par ??            eventWasRaised,\par ??            \cf5 "PropertyChanged on \{0\}"\cf0 , \cf1 this\cf0 .propertyName);\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NotifyExpectation&lt;/span&gt;&amp;lt;T&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;where&lt;/span&gt; T
: &lt;span style="color: #2b91af"&gt;INotifyPropertyChanged&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; T
owner;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; propertyName;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;bool&lt;/span&gt; eventExpected;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; NotifyExpectation(T
owner,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;string&lt;/span&gt; propertyName, &lt;span style="color: blue"&gt;bool&lt;/span&gt; eventExpected)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.owner
= owner;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.propertyName
= propertyName;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.eventExpected
= eventExpected;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; When(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;T&amp;gt;
action)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;bool&lt;/span&gt; eventWasRaised
= &lt;span style="color: blue"&gt;false&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.owner.PropertyChanged
+= (sender, e) =&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (e.PropertyName
== &lt;span style="color: blue"&gt;this&lt;/span&gt;.propertyName)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eventWasRaised = &lt;span style="color: blue"&gt;true&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; action(&lt;span style="color: blue"&gt;this&lt;/span&gt;.owner);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual&amp;lt;&lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.eventExpected,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; eventWasRaised,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"PropertyChanged
on {0}"&lt;/span&gt;, &lt;span style="color: blue"&gt;this&lt;/span&gt;.propertyName);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
You can replace the Assertion with one that matches your test framework of choice
(this one was written for MSTest).
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be02d84b-712f-4d40-ad4f-66e34bed4fc9" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,be02d84b-712f-4d40-ad4f-66e34bed4fc9.aspx</comments>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=d80f148c-cf4e-45fe-955f-02418a93bcde</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,d80f148c-cf4e-45fe-955f-02418a93bcde.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,d80f148c-cf4e-45fe-955f-02418a93bcde.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=d80f148c-cf4e-45fe-955f-02418a93bcde</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Since <a href="http://autofixture.codeplex.com/">AutoFixture</a><a href="http://blog.ploeh.dk/2009/07/01/AutoFixtureAsTestDataBuilder.aspx">is
a Test Data Builder</a>, one of its most important tasks is to build up graphs of
fully populated, yet semantically correct, strongly typed objects. As such, its default
behavior is to assign a value to every writable property in the object graph.
</p>
        <p>
While this is sometimes the desired behavior, at other times it is not.
</p>
        <p>
This is particularly the case when you want to test that a newly created object has
a property of a particular value. When you want to test the default value of a writable
property, AutoFixture's AutoProperty feature is very much in the way.
</p>
        <p>
Let's consider as an example a piece of software that deals with vehicle registration.
By default, a vehicle should have four wheels, since this is the most common occurrence.
Although I always practice TDD, I'll start by showing you the Vehicle class to illustrate
what I mean.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 Vehicle\par ??\cf0 \{\par ??    \cf1 public\cf0  Vehicle()\par ??    \{\par ??        \cf1 this\cf0 .Wheels = 4;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 int\cf0  Wheels \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Vehicle</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> Vehicle()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.Wheels
= 4;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">int</span> Wheels
{ <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Here's a test that ensures that the default number of wheels is <em>4</em> – or does
it?
</p>
        <p>
In fact the assertion fails because the actual value is <em>1</em>, not <em>4</em>.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  AnonymousVehicleHasWheelsAssignedByFixture()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 Vehicle\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 var\cf0  result = sut.Wheels;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&lt;\cf4 int\cf0 &gt;(4, result, \cf6 "Wheels"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> AnonymousVehicleHasWheelsAssignedByFixture()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Vehicle</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> result
= sut.Wheels;</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual&lt;<span style="color: blue">int</span>&gt;(4,
result, <span style="color: #a31515">"Wheels"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Why does the test fail when the value of Wheels is set to <em>4</em> in the constructor?
It fails because AutoFixture is designed to create <em>populated</em> test data, so
it assigns a value to every writable property. Wheels is a writable property, so AutoFixture
assigns an integer value to it using its <a href="http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture.aspx">default
algorithm for creating anonymous numbers</a>. Since no other numbers are being created
during this test, the number assigned to Wheels is <em>1</em>. This is AutoFixture's
AutoProperties feature in effect.
</p>
        <p>
When you want to test constructor logic, or otherwise wish to disable the AutoProperties
feature, you can use a <a href="http://blog.ploeh.dk/2009/05/26/TheAutoFixtureBuilder.aspx">customized
Builder</a> with the OmitAutoProperties method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  VehicleWithoutAutoPropertiesWillHaveFourWheels()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf4 var\cf0  sut = fixture.Build&lt;\cf3 Vehicle\cf0 &gt;()\par ??        .OmitAutoProperties()\par ??        .CreateAnonymous();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 var\cf0  result = sut.Wheels;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&lt;\cf4 int\cf0 &gt;(4, result, \cf6 "Wheels"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> VehicleWithoutAutoPropertiesWillHaveFourWheels()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.Build&lt;<span style="color: #2b91af">Vehicle</span>&gt;()</pre>
          <pre style="margin: 0px">        .OmitAutoProperties()</pre>
          <pre style="margin: 0px">        .CreateAnonymous();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> result
= sut.Wheels;</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual&lt;<span style="color: blue">int</span>&gt;(4,
result, <span style="color: #a31515">"Wheels"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The OmitAutoProperties method instructs AutoFixture to skip assigning automatic Anonymous
Values to all writable properties in the object graph. Any properties specifically
assigned by the <a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx">With
method</a> will still be assigned.
</p>
        <p>
The test using OmitAutoProperties succeeds.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d80f148c-cf4e-45fe-955f-02418a93bcde" />
      </body>
      <title>Disabling AutoProperties In AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,d80f148c-cf4e-45fe-955f-02418a93bcde.aspx</guid>
      <link>http://blog.ploeh.dk/2009/07/23/DisablingAutoPropertiesInAutoFixture.aspx</link>
      <pubDate>Thu, 23 Jul 2009 14:54:45 GMT</pubDate>
      <description>&lt;p&gt;
Since &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; &lt;a href="http://blog.ploeh.dk/2009/07/01/AutoFixtureAsTestDataBuilder.aspx"&gt;is
a Test Data Builder&lt;/a&gt;, one of its most important tasks is to build up graphs of
fully populated, yet semantically correct, strongly typed objects. As such, its default
behavior is to assign a value to every writable property in the object graph.
&lt;/p&gt;
&lt;p&gt;
While this is sometimes the desired behavior, at other times it is not.
&lt;/p&gt;
&lt;p&gt;
This is particularly the case when you want to test that a newly created object has
a property of a particular value. When you want to test the default value of a writable
property, AutoFixture's AutoProperty feature is very much in the way.
&lt;/p&gt;
&lt;p&gt;
Let's consider as an example a piece of software that deals with vehicle registration.
By default, a vehicle should have four wheels, since this is the most common occurrence.
Although I always practice TDD, I'll start by showing you the Vehicle class to illustrate
what I mean.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 Vehicle\par ??\cf0 \{\par ??    \cf1 public\cf0  Vehicle()\par ??    \{\par ??        \cf1 this\cf0 .Wheels = 4;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 int\cf0  Wheels \{ \cf1 get\cf0 ; \cf1 set\cf0 ; \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Vehicle&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; Vehicle()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Wheels
= 4;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; Wheels
{ &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Here's a test that ensures that the default number of wheels is &lt;em&gt;4&lt;/em&gt; – or does
it?
&lt;/p&gt;
&lt;p&gt;
In fact the assertion fails because the actual value is &lt;em&gt;1&lt;/em&gt;, not &lt;em&gt;4&lt;/em&gt;.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  AnonymousVehicleHasWheelsAssignedByFixture()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 Vehicle\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 var\cf0  result = sut.Wheels;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&amp;lt;\cf4 int\cf0 &amp;gt;(4, result, \cf6 "Wheels"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; AnonymousVehicleHasWheelsAssignedByFixture()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Vehicle&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; result
= sut.Wheels;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(4,
result, &lt;span style="color: #a31515"&gt;"Wheels"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Why does the test fail when the value of Wheels is set to &lt;em&gt;4&lt;/em&gt; in the constructor?
It fails because AutoFixture is designed to create &lt;em&gt;populated&lt;/em&gt; test data, so
it assigns a value to every writable property. Wheels is a writable property, so AutoFixture
assigns an integer value to it using its &lt;a href="http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture.aspx"&gt;default
algorithm for creating anonymous numbers&lt;/a&gt;. Since no other numbers are being created
during this test, the number assigned to Wheels is &lt;em&gt;1&lt;/em&gt;. This is AutoFixture's
AutoProperties feature in effect.
&lt;/p&gt;
&lt;p&gt;
When you want to test constructor logic, or otherwise wish to disable the AutoProperties
feature, you can use a &lt;a href="http://blog.ploeh.dk/2009/05/26/TheAutoFixtureBuilder.aspx"&gt;customized
Builder&lt;/a&gt; with the OmitAutoProperties method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  VehicleWithoutAutoPropertiesWillHaveFourWheels()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf4 var\cf0  sut = fixture.Build&amp;lt;\cf3 Vehicle\cf0 &amp;gt;()\par ??        .OmitAutoProperties()\par ??        .CreateAnonymous();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 var\cf0  result = sut.Wheels;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&amp;lt;\cf4 int\cf0 &amp;gt;(4, result, \cf6 "Wheels"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; VehicleWithoutAutoPropertiesWillHaveFourWheels()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;Vehicle&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .OmitAutoProperties()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; result
= sut.Wheels;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(4,
result, &lt;span style="color: #a31515"&gt;"Wheels"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The OmitAutoProperties method instructs AutoFixture to skip assigning automatic Anonymous
Values to all writable properties in the object graph. Any properties specifically
assigned by the &lt;a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx"&gt;With
method&lt;/a&gt; will still be assigned.
&lt;/p&gt;
&lt;p&gt;
The test using OmitAutoProperties succeeds.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=d80f148c-cf4e-45fe-955f-02418a93bcde" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,d80f148c-cf4e-45fe-955f-02418a93bcde.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2691f07e-2813-4c4e-a861-43d7d04be692</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2691f07e-2813-4c4e-a861-43d7d04be692</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The expressiveness of WPF is amazing. I particularly like the databinding and templating
features. The ability to selectively render an object based on its type is very strong.
</p>
        <p>
When I recently began working with ASP.NET MVC (which I like so far), I quickly ran
into a scenario where I would have liked to have WPF's DataTemplates at my disposal.
Maybe it's just because I've become used to WPF, but I missed the feature and set
out to find out if something similar is possible in ASP.NET MVC.
</p>
        <p>
Before we dive into that, I'd like to present the 'problem' in WPF terms, but the
underlying View Model that I want to expose will be shared between both solutions.
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PresentationModel" border="0" alt="PresentationModel" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/PresentationModel_3.png" width="619" height="629" />
        </p>
        <p>
The main point is that the <em>Items</em> property exposes a polymorphic list. While
all items in this list share a common property (Name), they are otherwise different;
one contains a piece of Text, one contains a Color, and one is a complex item that
contains child items.
</p>
        <p>
When I render this list, I want each item to render according to its type.
</p>
        <p>
In WPF, this is fairly easy to accomplish with DataTemplates:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &lt;\cf3 ListBox.Resources\cf1 &gt;\par ??\cf3     \cf1 &lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedTextItem\cf1 \}"&gt;\par ??\cf3         \cf1 &lt;\cf3 StackPanel\cf1 &gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&gt;\par ??\cf3         \cf1 &lt;/\cf3 StackPanel\cf1 &gt;\par ??\cf3     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??\cf3     \cf1 &lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedColorItem\cf1 \}"&gt;\par ??\cf3         \cf1 &lt;\cf3 StackPanel\cf1 &gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&gt;\par ??\cf3             \cf1 &lt;\cf3 Ellipse\cf4  Height\cf1 ="25"\cf4  Width\cf1 ="25"\par ??\cf0                     \cf4  HorizontalAlignment\cf1 ="Left"\par ??\cf0                     \cf4  Fill\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Brush\}"\par ??\cf0                     \cf4  Stroke\cf1 ="DarkGray" /&gt;\par ??\cf3         \cf1 &lt;/\cf3 StackPanel\cf1 &gt;\par ??\cf3     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??\cf3     \cf1 &lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedComplexItem\cf1 \}"&gt;\par ??\cf3         \cf1 &lt;\cf3 StackPanel\cf1 &gt;\par ??\cf3             \cf1 &lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&gt;\par ??\cf3             \cf1 &lt;\cf3 ListBox\cf4  ItemsSource\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Children\}"\par ??\cf0                     \cf4  BorderThickness\cf1 ="0"&gt;\par ??\cf3                 \cf1 &lt;\cf3 ListBox.Resources\cf1 &gt;\par ??\cf3                     \cf1 &lt;\cf3 DataTemplate\par ??\cf0                        \cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 ChildItem\cf1 \}"&gt;\par ??\cf3                         \cf1 &lt;\cf3 TextBlock\par ??\cf0                            \cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&gt;\par ??\cf3                     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??\cf3                 \cf1 &lt;/\cf3 ListBox.Resources\cf1 &gt;\par ??\cf3             \cf1 &lt;/\cf3 ListBox\cf1 &gt;\par ??\cf3         \cf1 &lt;/\cf3 StackPanel\cf1 &gt;\par ??\cf3     \cf1 &lt;/\cf3 DataTemplate\cf1 &gt;\par ??&lt;/\cf3 ListBox.Resources\cf1 &gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: red"> DataType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type</span>
            <span style="color: red"> pm</span>
            <span style="color: blue">:</span>
            <span style="color: red">NamedTextItem</span>
            <span style="color: blue">}"&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Name}"</span>
          </pre>
          <pre style="margin: 0px">                      <span style="color: red"> FontWeight</span><span style="color: blue">="bold"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Text}"
/&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: red"> DataType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type</span>
            <span style="color: red"> pm</span>
            <span style="color: blue">:</span>
            <span style="color: red">NamedColorItem</span>
            <span style="color: blue">}"&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Name}"</span>
          </pre>
          <pre style="margin: 0px">                      <span style="color: red"> FontWeight</span><span style="color: blue">="bold"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">Ellipse</span>
            <span style="color: red"> Height</span>
            <span style="color: blue">="25"</span>
            <span style="color: red"> Width</span>
            <span style="color: blue">="25"</span>
          </pre>
          <pre style="margin: 0px">                    <span style="color: red"> HorizontalAlignment</span><span style="color: blue">="Left"</span></pre>
          <pre style="margin: 0px">                    <span style="color: red"> Fill</span><span style="color: blue">="{</span><span style="color: #a31515">Binding</span><span style="color: red"> Path</span><span style="color: blue">=Brush}"</span></pre>
          <pre style="margin: 0px">                    <span style="color: red"> Stroke</span><span style="color: blue">="DarkGray"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: red"> DataType</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">x</span>
            <span style="color: blue">:</span>
            <span style="color: #a31515">Type</span>
            <span style="color: red"> pm</span>
            <span style="color: blue">:</span>
            <span style="color: red">NamedComplexItem</span>
            <span style="color: blue">}"&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
            <span style="color: red"> Text</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Name}"</span>
          </pre>
          <pre style="margin: 0px">                      <span style="color: red"> FontWeight</span><span style="color: blue">="bold"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">ListBox</span>
            <span style="color: red"> ItemsSource</span>
            <span style="color: blue">="{</span>
            <span style="color: #a31515">Binding</span>
            <span style="color: red"> Path</span>
            <span style="color: blue">=Children}"</span>
          </pre>
          <pre style="margin: 0px">                    <span style="color: red"> BorderThickness</span><span style="color: blue">="0"&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                    </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">DataTemplate</span>
          </pre>
          <pre style="margin: 0px">                       <span style="color: red"> DataType</span><span style="color: blue">="{</span><span style="color: #a31515">x</span><span style="color: blue">:</span><span style="color: #a31515">Type</span><span style="color: red"> pm</span><span style="color: blue">:</span><span style="color: red">ChildItem</span><span style="color: blue">}"&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                        </span>
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">TextBlock</span>
          </pre>
          <pre style="margin: 0px">                           <span style="color: red"> Text</span><span style="color: blue">="{</span><span style="color: #a31515">Binding</span><span style="color: red"> Path</span><span style="color: blue">=Text}"
/&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">                </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">            </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">ListBox</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">        </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">StackPanel</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #a31515">    </span>
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">DataTemplate</span>
            <span style="color: blue">&gt;</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;/</span>
            <span style="color: #a31515">ListBox.Resources</span>
            <span style="color: blue">&gt;</span>
          </pre>
        </div>
        <p>
Each DataTemplate is contained within a ListBox. When the ListBox binds to each item
in the <em>Items</em> list, it automatically picks the correct template for the item.
</p>
        <p>
The result is something like this:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="WpfApp" border="0" alt="WpfApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/WpfApp_5.png" width="167" height="333" />
        </p>
        <p>
The NamedTextItem is rendered as a box containing the Name and the Text on two separate
lines; the NamedColorItem is rendered as a box containing the Name and a circle filled
with the Color defined by the item; and the NamedComplexItem is rendered as a box
with the Name and each child of the Children list.
</p>
        <p>
This is all implemented declaratively without a single line of imperative UI code.
</p>
        <p>
Is it possible to do the same in ASP.NET MVC?
</p>
        <p>
To my knowledge (but please correct me if I'm wrong), ASP.NET MVC has no explicit
concept of a DataTemplate, so we will have to mimic it. The following describes the
best I've been able to come up with so far.
</p>
        <p>
In ASP.NET MVC, there's no declarative databinding, so we will need to loop through
the list of items. My View page derives from ViewPage&lt;MyViewModel&gt;, so I can
write
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&gt;\par ??\cf0    \cb2\highlight2 &lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;/\cf5 div\cf4 &gt;\par ??\cf0\cb2\highlight2 &lt;%\cb0\highlight0  \} \cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">foreach</span> (<span style="color: blue">var</span> item <span style="color: blue">in</span><span style="color: blue">this</span>.Model.Items)</pre>
          <pre style="margin: 0px">   { <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;</span><span style="color: #a31515">div</span><span style="color: red">class</span><span style="color: blue">="ploeh"&gt;</span></pre>
          <pre style="margin: 0px">   <span style="background: #ffee62">&lt;%</span><span style="color: green">//
Render each item </span><span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span> } <span style="background: #ffee62">%&gt;</span></pre>
        </div>
        <p>
The challenge is to figure out how to render each item according to its own template.
</p>
        <p>
To define the templates, I create a UserControl for each item. The NamedTextItemUserControl
derives from ViewUserControl&lt;NamedTextItem&gt;, which gives me a strongly typed
Model:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &lt;\cf3 div\cf1 &gt;&lt;\cf3 strong\cf1 &gt;\cf0\cb5\highlight5 &lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Name \cb5\highlight5 %&gt;\cf1\cb0\highlight0 &lt;/\cf3 strong\cf1 &gt;&lt;/\cf3 div\cf1 &gt;\par ??&lt;\cf3 div\cf1 &gt;\cf0\cb5\highlight5 &lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Text \cb5\highlight5 %&gt;\cf1\cb0\highlight0 &lt;/\cf3 div\cf1 &gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">div</span>
            <span style="color: blue">&gt;&lt;</span>
            <span style="color: #a31515">strong</span>
            <span style="color: blue">&gt;</span>
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">=</span>
            <span style="color: blue">this</span>.Model.Name <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">strong</span><span style="color: blue">&gt;&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">div</span>
            <span style="color: blue">&gt;</span>
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">=</span>
            <span style="color: blue">this</span>.Model.Text <span style="background: #ffee62">%&gt;</span><span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
        </div>
        <p>
The other two UserControls are implemented similarly.
</p>
        <p>
A UserControl can be rendered using the RenderPartial extension method, so the only
thing left is to select the correct UserControl name for each item. It would be nice
to be able to do this in markup, like WPF, but I'm not aware of any way that is possible.
</p>
        <p>
I will have to resort to code, but we can at least strive for code that is as declarative
in style as possible.
</p>
        <p>
First, I need to define the map from type to UserControl:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cb2\highlight2 &lt;%\par ??\cb0\highlight0     \cf4 var\cf0  dataTemplates = \cf4 new\cf0  \cf5 Dictionary\cf0 &lt;\cf5 Type\cf0 , \cf4 string\cf0 &gt;();\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedTextItem\cf0 )] =\par ??        \cf6 "NamedTextItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedColorItem\cf0 )] =\par ??        \cf6 "NamedColorItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedComplexItem\cf0 )] =\par ??        \cf6 "NamedComplexItemUserControl"\cf0 ;\par ??\cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
          </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> dataTemplates
= <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: blue">string</span>&gt;();</pre>
          <pre style="margin: 0px">    dataTemplates[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NamedTextItem</span>)]
=</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"NamedTextItemUserControl"</span>;</pre>
          <pre style="margin: 0px">    dataTemplates[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NamedColorItem</span>)]
=</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"NamedColorItemUserControl"</span>;</pre>
          <pre style="margin: 0px">    dataTemplates[<span style="color: blue">typeof</span>(<span style="color: #2b91af">NamedComplexItem</span>)]
=</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"NamedComplexItemUserControl"</span>;</pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">%&gt;</span>
          </pre>
        </div>
        <p>
Next, I can use this map to render each item correctly:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&gt;\par ??\cf0    \cb2\highlight2 &lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cb2\highlight2 &lt;%\cb0\highlight0  \cf4 this\cf0 .Html.RenderPartial(dataTemplates[item.GetType()],\par ??                             item); \cb2\highlight2 %&gt;\par ??\cb0\highlight0    \cf4 &lt;/\cf5 div\cf4 &gt;\par ??\cf0\cb2\highlight2 &lt;%\cb0\highlight0  \} \cb2\highlight2 %&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span>
            <span style="color: blue">foreach</span> (<span style="color: blue">var</span> item <span style="color: blue">in</span><span style="color: blue">this</span>.Model.Items)</pre>
          <pre style="margin: 0px">   { <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;</span><span style="color: #a31515">div</span><span style="color: red">class</span><span style="color: blue">="ploeh"&gt;</span></pre>
          <pre style="margin: 0px">   <span style="background: #ffee62">&lt;%</span><span style="color: green">//
Render each item </span><span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="background: #ffee62">&lt;%</span><span style="color: blue">this</span>.Html.RenderPartial(dataTemplates[item.GetType()],</pre>
          <pre style="margin: 0px">                            item); <span style="background: #ffee62">%&gt;</span></pre>
          <pre style="margin: 0px">   <span style="color: blue">&lt;/</span><span style="color: #a31515">div</span><span style="color: blue">&gt;</span></pre>
          <pre style="margin: 0px">
            <span style="background: #ffee62">&lt;%</span> } <span style="background: #ffee62">%&gt;</span></pre>
        </div>
        <p>
This is definitely less pretty than with WPF, but if you overlook the aesthetics and
focus on the structure of the code, it's darn close to markup. The Cyclomatic Complexity
of the page is only <em>2</em>, and that's even because of the <em>foreach</em> statement
that we need in any case.
</p>
        <p>
The resulting page looks like this:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="AspNetMvcApp" border="0" alt="AspNetMvcApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/AspNetMvcApp_1.png" width="156" height="246" />
        </p>
        <p>
My HTML skills aren't good enough to draw circles with markup, so I had to replace
them with blocks, but apart from that, the result is pretty much the same.
</p>
        <p>
A potential improvement on this technique could be to embed the knowledge of the UserControl
into each item. ASP.NET MVC Controllers already know of Views in an abstract sense,
so letting the View Model know about a UserControl (identified as a string) may be
conceptually sound.
</p>
        <p>
The advantage would be that we could get rid of the Dictionary in the ViewPage and
instead let the item itself tell us the name of the UserControl that should be used
to render it.
</p>
        <p>
The disadvantage would be that we lose some flexibility. It would then require a recompilation
of the application if we wanted to render an item using a different UserControl.
</p>
        <p>
The technique outlined here represents an explorative work in progress, so comments
are welcome.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2691f07e-2813-4c4e-a861-43d7d04be692" />
      </body>
      <title>DataTemplating In ASP.NET MVC</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</guid>
      <link>http://blog.ploeh.dk/2009/07/16/DataTemplatingInASPNETMVC.aspx</link>
      <pubDate>Thu, 16 Jul 2009 19:33:48 GMT</pubDate>
      <description>&lt;p&gt;
The expressiveness of WPF is amazing. I particularly like the databinding and templating
features. The ability to selectively render an object based on its type is very strong.
&lt;/p&gt;
&lt;p&gt;
When I recently began working with ASP.NET MVC (which I like so far), I quickly ran
into a scenario where I would have liked to have WPF's DataTemplates at my disposal.
Maybe it's just because I've become used to WPF, but I missed the feature and set
out to find out if something similar is possible in ASP.NET MVC.
&lt;/p&gt;
&lt;p&gt;
Before we dive into that, I'd like to present the 'problem' in WPF terms, but the
underlying View Model that I want to expose will be shared between both solutions.
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PresentationModel" border="0" alt="PresentationModel" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/PresentationModel_3.png" width="619" height="629"&gt; 
&lt;/p&gt;
&lt;p&gt;
The main point is that the &lt;em&gt;Items&lt;/em&gt; property exposes a polymorphic list. While
all items in this list share a common property (Name), they are otherwise different;
one contains a piece of Text, one contains a Color, and one is a complex item that
contains child items.
&lt;/p&gt;
&lt;p&gt;
When I render this list, I want each item to render according to its type.
&lt;/p&gt;
&lt;p&gt;
In WPF, this is fairly easy to accomplish with DataTemplates:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &amp;lt;\cf3 ListBox.Resources\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedTextItem\cf1 \}"&amp;gt;\par ??\cf3         \cf1 &amp;lt;\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&amp;gt;\par ??\cf3         \cf1 &amp;lt;/\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedColorItem\cf1 \}"&amp;gt;\par ??\cf3         \cf1 &amp;lt;\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 Ellipse\cf4  Height\cf1 ="25"\cf4  Width\cf1 ="25"\par ??\cf0                     \cf4  HorizontalAlignment\cf1 ="Left"\par ??\cf0                     \cf4  Fill\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Brush\}"\par ??\cf0                     \cf4  Stroke\cf1 ="DarkGray" /&amp;gt;\par ??\cf3         \cf1 &amp;lt;/\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;\cf3 DataTemplate\cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 NamedComplexItem\cf1 \}"&amp;gt;\par ??\cf3         \cf1 &amp;lt;\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 TextBlock\cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Name\}"\par ??\cf0                       \cf4  FontWeight\cf1 ="bold" /&amp;gt;\par ??\cf3             \cf1 &amp;lt;\cf3 ListBox\cf4  ItemsSource\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Children\}"\par ??\cf0                     \cf4  BorderThickness\cf1 ="0"&amp;gt;\par ??\cf3                 \cf1 &amp;lt;\cf3 ListBox.Resources\cf1 &amp;gt;\par ??\cf3                     \cf1 &amp;lt;\cf3 DataTemplate\par ??\cf0                        \cf4  DataType\cf1 ="\{\cf3 x\cf1 :\cf3 Type\cf4  pm\cf1 :\cf4 ChildItem\cf1 \}"&amp;gt;\par ??\cf3                         \cf1 &amp;lt;\cf3 TextBlock\par ??\cf0                            \cf4  Text\cf1 ="\{\cf3 Binding\cf4  Path\cf1 =Text\}" /&amp;gt;\par ??\cf3                     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??\cf3                 \cf1 &amp;lt;/\cf3 ListBox.Resources\cf1 &amp;gt;\par ??\cf3             \cf1 &amp;lt;/\cf3 ListBox\cf1 &amp;gt;\par ??\cf3         \cf1 &amp;lt;/\cf3 StackPanel\cf1 &amp;gt;\par ??\cf3     \cf1 &amp;lt;/\cf3 DataTemplate\cf1 &amp;gt;\par ??&amp;lt;/\cf3 ListBox.Resources\cf1 &amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;NamedTextItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Name}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;="bold"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Text}"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;NamedColorItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Name}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;="bold"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;Ellipse&lt;/span&gt;&lt;span style="color: red"&gt; Height&lt;/span&gt;&lt;span style="color: blue"&gt;="25"&lt;/span&gt;&lt;span style="color: red"&gt; Width&lt;/span&gt;&lt;span style="color: blue"&gt;="25"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; HorizontalAlignment&lt;/span&gt;&lt;span style="color: blue"&gt;="Left"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; Fill&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Brush}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; Stroke&lt;/span&gt;&lt;span style="color: blue"&gt;="DarkGray"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;NamedComplexItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Name}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; FontWeight&lt;/span&gt;&lt;span style="color: blue"&gt;="bold"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox&lt;/span&gt;&lt;span style="color: red"&gt; ItemsSource&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Children}"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; BorderThickness&lt;/span&gt;&lt;span style="color: blue"&gt;="0"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; DataType&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;x&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: #a31515"&gt;Type&lt;/span&gt;&lt;span style="color: red"&gt; pm&lt;/span&gt;&lt;span style="color: blue"&gt;:&lt;/span&gt;&lt;span style="color: red"&gt;ChildItem&lt;/span&gt;&lt;span style="color: blue"&gt;}"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;TextBlock&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: red"&gt; Text&lt;/span&gt;&lt;span style="color: blue"&gt;="{&lt;/span&gt;&lt;span style="color: #a31515"&gt;Binding&lt;/span&gt;&lt;span style="color: red"&gt; Path&lt;/span&gt;&lt;span style="color: blue"&gt;=Text}"
/&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;StackPanel&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #a31515"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;DataTemplate&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;ListBox.Resources&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Each DataTemplate is contained within a ListBox. When the ListBox binds to each item
in the &lt;em&gt;Items&lt;/em&gt; list, it automatically picks the correct template for the item.
&lt;/p&gt;
&lt;p&gt;
The result is something like this:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="WpfApp" border="0" alt="WpfApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/WpfApp_5.png" width="167" height="333"&gt; 
&lt;/p&gt;
&lt;p&gt;
The NamedTextItem is rendered as a box containing the Name and the Text on two separate
lines; the NamedColorItem is rendered as a box containing the Name and a circle filled
with the Color defined by the item; and the NamedComplexItem is rendered as a box
with the Name and each child of the Children list.
&lt;/p&gt;
&lt;p&gt;
This is all implemented declaratively without a single line of imperative UI code.
&lt;/p&gt;
&lt;p&gt;
Is it possible to do the same in ASP.NET MVC?
&lt;/p&gt;
&lt;p&gt;
To my knowledge (but please correct me if I'm wrong), ASP.NET MVC has no explicit
concept of a DataTemplate, so we will have to mimic it. The following describes the
best I've been able to come up with so far.
&lt;/p&gt;
&lt;p&gt;
In ASP.NET MVC, there's no declarative databinding, so we will need to loop through
the list of items. My View page derives from ViewPage&amp;lt;MyViewModel&amp;gt;, so I can
write
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&amp;gt;\par ??\cf0    \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;/\cf5 div\cf4 &amp;gt;\par ??\cf0\cb2\highlight2 &amp;lt;%\cb0\highlight0  \} \cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue"&gt;var&lt;/span&gt; item &lt;span style="color: blue"&gt;in&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Items)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; { &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt; &lt;span style="color: red"&gt;class&lt;/span&gt;&lt;span style="color: blue"&gt;="ploeh"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: green"&gt;//
Render each item &lt;/span&gt;&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; } &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The challenge is to figure out how to render each item according to its own template.
&lt;/p&gt;
&lt;p&gt;
To define the templates, I create a UserControl for each item. The NamedTextItemUserControl
derives from ViewUserControl&amp;lt;NamedTextItem&amp;gt;, which gives me a strongly typed
Model:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red0\green0\blue0;\red255\green238\blue98;}??\fs20 \cf1 &amp;lt;\cf3 div\cf1 &amp;gt;&amp;lt;\cf3 strong\cf1 &amp;gt;\cf0\cb5\highlight5 &amp;lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Name \cb5\highlight5 %&amp;gt;\cf1\cb0\highlight0 &amp;lt;/\cf3 strong\cf1 &amp;gt;&amp;lt;/\cf3 div\cf1 &amp;gt;\par ??&amp;lt;\cf3 div\cf1 &amp;gt;\cf0\cb5\highlight5 &amp;lt;%\cf1\cb0\highlight0 =\cf0  \cf1 this\cf0 .Model.Text \cb5\highlight5 %&amp;gt;\cf1\cb0\highlight0 &amp;lt;/\cf3 div\cf1 &amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;strong&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Name &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;strong&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Text &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The other two UserControls are implemented similarly.
&lt;/p&gt;
&lt;p&gt;
A UserControl can be rendered using the RenderPartial extension method, so the only
thing left is to select the correct UserControl name for each item. It would be nice
to be able to do this in markup, like WPF, but I'm not aware of any way that is possible.
&lt;/p&gt;
&lt;p&gt;
I will have to resort to code, but we can at least strive for code that is as declarative
in style as possible.
&lt;/p&gt;
&lt;p&gt;
First, I need to define the map from type to UserControl:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cb2\highlight2 &amp;lt;%\par ??\cb0\highlight0     \cf4 var\cf0  dataTemplates = \cf4 new\cf0  \cf5 Dictionary\cf0 &amp;lt;\cf5 Type\cf0 , \cf4 string\cf0 &amp;gt;();\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedTextItem\cf0 )] =\par ??        \cf6 "NamedTextItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedColorItem\cf0 )] =\par ??        \cf6 "NamedColorItemUserControl"\cf0 ;\par ??    dataTemplates[\cf4 typeof\cf0 (\cf5 NamedComplexItem\cf0 )] =\par ??        \cf6 "NamedComplexItemUserControl"\cf0 ;\par ??\cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; dataTemplates
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataTemplates[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;NamedTextItem&lt;/span&gt;)]
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"NamedTextItemUserControl"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataTemplates[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;NamedColorItem&lt;/span&gt;)]
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"NamedColorItemUserControl"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; dataTemplates[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;NamedComplexItem&lt;/span&gt;)]
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"NamedComplexItemUserControl"&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Next, I can use this map to render each item correctly:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green238\blue98;\red255\green255\blue255;\red0\green0\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green128\blue0;}??\fs20 \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf4 foreach\cf0  (\cf4 var\cf0  item \cf4 in\cf0  \cf4 this\cf0 .Model.Items)\par ??   \{ \cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;\cf5 div\cf0  \cf6 class\cf4 ="ploeh"&amp;gt;\par ??\cf0    \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf7 // Render each item \cf0\cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cb2\highlight2 &amp;lt;%\cb0\highlight0  \cf4 this\cf0 .Html.RenderPartial(dataTemplates[item.GetType()],\par ??                             item); \cb2\highlight2 %&amp;gt;\par ??\cb0\highlight0    \cf4 &amp;lt;/\cf5 div\cf4 &amp;gt;\par ??\cf0\cb2\highlight2 &amp;lt;%\cb0\highlight0  \} \cb2\highlight2 %&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue"&gt;var&lt;/span&gt; item &lt;span style="color: blue"&gt;in&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Model.Items)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; { &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt; &lt;span style="color: red"&gt;class&lt;/span&gt;&lt;span style="color: blue"&gt;="ploeh"&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: green"&gt;//
Render each item &lt;/span&gt;&lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Html.RenderPartial(dataTemplates[item.GetType()],&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; item); &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;&amp;lt;/&lt;/span&gt;&lt;span style="color: #a31515"&gt;div&lt;/span&gt;&lt;span style="color: blue"&gt;&amp;gt;&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="background: #ffee62"&gt;&amp;lt;%&lt;/span&gt; } &lt;span style="background: #ffee62"&gt;%&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is definitely less pretty than with WPF, but if you overlook the aesthetics and
focus on the structure of the code, it's darn close to markup. The Cyclomatic Complexity
of the page is only &lt;em&gt;2&lt;/em&gt;, and that's even because of the &lt;em&gt;foreach&lt;/em&gt; statement
that we need in any case.
&lt;/p&gt;
&lt;p&gt;
The resulting page looks like this:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="AspNetMvcApp" border="0" alt="AspNetMvcApp" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/DataTemplatingInASP.NETMVC_13643/AspNetMvcApp_1.png" width="156" height="246"&gt; 
&lt;/p&gt;
&lt;p&gt;
My HTML skills aren't good enough to draw circles with markup, so I had to replace
them with blocks, but apart from that, the result is pretty much the same.
&lt;/p&gt;
&lt;p&gt;
A potential improvement on this technique could be to embed the knowledge of the UserControl
into each item. ASP.NET MVC Controllers already know of Views in an abstract sense,
so letting the View Model know about a UserControl (identified as a string) may be
conceptually sound.
&lt;/p&gt;
&lt;p&gt;
The advantage would be that we could get rid of the Dictionary in the ViewPage and
instead let the item itself tell us the name of the UserControl that should be used
to render it.
&lt;/p&gt;
&lt;p&gt;
The disadvantage would be that we lose some flexibility. It would then require a recompilation
of the application if we wanted to render an item using a different UserControl.
&lt;/p&gt;
&lt;p&gt;
The technique outlined here represents an explorative work in progress, so comments
are welcome.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2691f07e-2813-4c4e-a861-43d7d04be692" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2691f07e-2813-4c4e-a861-43d7d04be692.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>WPF</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=f96fb271-9bf0-4153-8c2e-f25245012892</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,f96fb271-9bf0-4153-8c2e-f25245012892.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,f96fb271-9bf0-4153-8c2e-f25245012892.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=f96fb271-9bf0-4153-8c2e-f25245012892</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
A couple of days ago I released <a href="http://autofixture.codeplex.com/">AutoFixture</a> .8.4.
It contains a few small feature additions and a bug fix. You can get it at the <a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29096">AutoFixture
CodePlex site</a> as usual.
</p>
        <p>
You may have noticed that I'm frequently releasing incremental versions these days.
This is because we have begun using AutoFixture for writing production software at <a href="http://www.safewhere.net/">Safewhere</a>.
So far, it has been a pleasure to use AutoFixture in my daily work, and watch colleagues
pick it up and run with it.
</p>
        <p>
Such intensive usage obviously uncovers missing features as well as a few bugs, which
is the driving force behind the frequent releases. I've been happy to observe that
so far, there have been only a few bugs, and the general API is very expressive and
useful.
</p>
        <p>
After we ship the first product written with AutoFixture, I plan to upgrade it to
version .9 (beta). That should hopefully happen in the autumn of 2009.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f96fb271-9bf0-4153-8c2e-f25245012892" />
      </body>
      <title>AutoFixture .8.4 And Roadmap</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,f96fb271-9bf0-4153-8c2e-f25245012892.aspx</guid>
      <link>http://blog.ploeh.dk/2009/07/11/AutoFixture84AndRoadmap.aspx</link>
      <pubDate>Sat, 11 Jul 2009 20:35:34 GMT</pubDate>
      <description>&lt;p&gt;
A couple of days ago I released &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; .8.4.
It contains a few small feature additions and a bug fix. You can get it at the &lt;a href="http://autofixture.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=29096"&gt;AutoFixture
CodePlex site&lt;/a&gt; as usual.
&lt;/p&gt;
&lt;p&gt;
You may have noticed that I'm frequently releasing incremental versions these days.
This is because we have begun using AutoFixture for writing production software at &lt;a href="http://www.safewhere.net/"&gt;Safewhere&lt;/a&gt;.
So far, it has been a pleasure to use AutoFixture in my daily work, and watch colleagues
pick it up and run with it.
&lt;/p&gt;
&lt;p&gt;
Such intensive usage obviously uncovers missing features as well as a few bugs, which
is the driving force behind the frequent releases. I've been happy to observe that
so far, there have been only a few bugs, and the general API is very expressive and
useful.
&lt;/p&gt;
&lt;p&gt;
After we ship the first product written with AutoFixture, I plan to upgrade it to
version .9 (beta). That should hopefully happen in the autumn of 2009.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f96fb271-9bf0-4153-8c2e-f25245012892" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,f96fb271-9bf0-4153-8c2e-f25245012892.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=20eacbdc-fcb2-4dc0-9024-c3735cb762a3</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,20eacbdc-fcb2-4dc0-9024-c3735cb762a3.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,20eacbdc-fcb2-4dc0-9024-c3735cb762a3.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=20eacbdc-fcb2-4dc0-9024-c3735cb762a3</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Some time ago, my good friend Martin Gildenpfennig from <a href="http://www.ative.dk/">Ative</a> made
me aware that <a href="http://autofixture.codeplex.com/">AutoFixture</a> (among other
things) is an generic implementation of the <a href="http://www.natpryce.com/articles/000714.html">Test
Data Builder</a> pattern, and indeed it is.
</p>
        <p>
In the original Gang of Four definition of a Design Pattern, several people must independently
have arrived at the same general solution to a given problem before we can call a
coding idiom a true Pattern. In this spirit, the Test Data Builder pattern is on the
verge of becoming a true Design Pattern, since I came up with AutoFixture without
having heard about Test Data Builder :)
</p>
        <p>
The problem is the same: How do we create semantically correct test objects in a manner
that is flexible and yet hides away irrelevant complexity?
</p>
        <p>
Like others before me, I tried the Object Mother (anti?)pattern and found it lacking.
To me the answer was AutoFixture, a library that heuristically builds object graphs
using Reflection and built-in rules for specific types.
</p>
        <p>
Although my original approach was different, you can certainly use AutoFixture as
a generic Test Data Builder.
</p>
        <p>
To demonstrate this, let's work with this (oversimplified) Order object model:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/AutoFixtureAsTestDataBuilder_1371F/image_3.png" width="478" height="457" />
        </p>
        <p>
Assuming that we have an instance of the Fixture class (called <em>fixture</em>),
we can create a new instance of the Order class with a ShippingAddress in Denmark:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  order = fixture.Build&lt;\cf4 Order\cf0 &gt;()\par ??    .With(o =&gt; o.ShippingAddress, \par ??        fixture.Build&lt;\cf4 Address\cf0 &gt;()\par ??        .With(a =&gt; a.Country, \cf5 "Denmark"\cf0 )\par ??        .CreateAnonymous())\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= fixture.Build&lt;<span style="color: #2b91af">Order</span>&gt;()</pre>
          <pre style="margin: 0px">    .With(o =&gt; o.ShippingAddress, </pre>
          <pre style="margin: 0px">        fixture.Build&lt;<span style="color: #2b91af">Address</span>&gt;()</pre>
          <pre style="margin: 0px">        .With(a =&gt; a.Country, <span style="color: #a31515">"Denmark"</span>)</pre>
          <pre style="margin: 0px">        .CreateAnonymous())</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
While this works and follows the Test Data Builder pattern, I find this more concise
and readable:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  order = fixture.CreateAnonymous&lt;\cf4 Order\cf0 &gt;();\par ??order.ShippingAddress.Country = \cf5 "Denmark"\cf0 ;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Order</span>&gt;();</pre>
          <pre style="margin: 0px">order.ShippingAddress.Country = <span style="color: #a31515">"Denmark"</span>;</pre>
        </div>
        <p>
The result is the same.
</p>
        <p>
We can also add anonymous order lines to the order using this fluent interface:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  order = fixture.Build&lt;\cf4 Order\cf0 &gt;()\par ??    .Do(o =&gt; fixture.AddManyTo(o.OrderLines))\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= fixture.Build&lt;<span style="color: #2b91af">Order</span>&gt;()</pre>
          <pre style="margin: 0px">    .Do(o =&gt; fixture.AddManyTo(o.OrderLines))</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
but again, I find it easier to simply let AutoFixture create a fully anonymous Order
instance, and then afterwards modify the relevant parts:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  order = fixture.CreateAnonymous&lt;\cf4 Order\cf0 &gt;();\par ??fixture.AddManyTo(order.OrderLines);}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Order</span>&gt;();</pre>
          <pre style="margin: 0px">fixture.AddManyTo(order.OrderLines);</pre>
        </div>
        <p>
Whether you prefer one style over the other, AutoFixture supports them both.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=20eacbdc-fcb2-4dc0-9024-c3735cb762a3" />
      </body>
      <title>AutoFixture As Test Data Builder</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,20eacbdc-fcb2-4dc0-9024-c3735cb762a3.aspx</guid>
      <link>http://blog.ploeh.dk/2009/07/01/AutoFixtureAsTestDataBuilder.aspx</link>
      <pubDate>Wed, 01 Jul 2009 06:19:00 GMT</pubDate>
      <description>&lt;p&gt;
Some time ago, my good friend Martin Gildenpfennig from &lt;a href="http://www.ative.dk/"&gt;Ative&lt;/a&gt; made
me aware that &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; (among other
things) is an generic implementation of the &lt;a href="http://www.natpryce.com/articles/000714.html"&gt;Test
Data Builder&lt;/a&gt; pattern, and indeed it is.
&lt;/p&gt;
&lt;p&gt;
In the original Gang of Four definition of a Design Pattern, several people must independently
have arrived at the same general solution to a given problem before we can call a
coding idiom a true Pattern. In this spirit, the Test Data Builder pattern is on the
verge of becoming a true Design Pattern, since I came up with AutoFixture without
having heard about Test Data Builder :)
&lt;/p&gt;
&lt;p&gt;
The problem is the same: How do we create semantically correct test objects in a manner
that is flexible and yet hides away irrelevant complexity?
&lt;/p&gt;
&lt;p&gt;
Like others before me, I tried the Object Mother (anti?)pattern and found it lacking.
To me the answer was AutoFixture, a library that heuristically builds object graphs
using Reflection and built-in rules for specific types.
&lt;/p&gt;
&lt;p&gt;
Although my original approach was different, you can certainly use AutoFixture as
a generic Test Data Builder.
&lt;/p&gt;
&lt;p&gt;
To demonstrate this, let's work with this (oversimplified) Order object model:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/AutoFixtureAsTestDataBuilder_1371F/image_3.png" width="478" height="457"&gt; 
&lt;/p&gt;
&lt;p&gt;
Assuming that we have an instance of the Fixture class (called &lt;em&gt;fixture&lt;/em&gt;),
we can create a new instance of the Order class with a ShippingAddress in Denmark:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  order = fixture.Build&amp;lt;\cf4 Order\cf0 &amp;gt;()\par ??    .With(o =&amp;gt; o.ShippingAddress, \par ??        fixture.Build&amp;lt;\cf4 Address\cf0 &amp;gt;()\par ??        .With(a =&amp;gt; a.Country, \cf5 "Denmark"\cf0 )\par ??        .CreateAnonymous())\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(o =&amp;gt; o.ShippingAddress, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;Address&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(a =&amp;gt; a.Country, &lt;span style="color: #a31515"&gt;"Denmark"&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous())&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
While this works and follows the Test Data Builder pattern, I find this more concise
and readable:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  order = fixture.CreateAnonymous&amp;lt;\cf4 Order\cf0 &amp;gt;();\par ??order.ShippingAddress.Country = \cf5 "Denmark"\cf0 ;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;order.ShippingAddress.Country = &lt;span style="color: #a31515"&gt;"Denmark"&lt;/span&gt;;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The result is the same.
&lt;/p&gt;
&lt;p&gt;
We can also add anonymous order lines to the order using this fluent interface:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  order = fixture.Build&amp;lt;\cf4 Order\cf0 &amp;gt;()\par ??    .Do(o =&amp;gt; fixture.AddManyTo(o.OrderLines))\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Do(o =&amp;gt; fixture.AddManyTo(o.OrderLines))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
but again, I find it easier to simply let AutoFixture create a fully anonymous Order
instance, and then afterwards modify the relevant parts:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  order = fixture.CreateAnonymous&amp;lt;\cf4 Order\cf0 &amp;gt;();\par ??fixture.AddManyTo(order.OrderLines);}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.AddManyTo(order.OrderLines);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Whether you prefer one style over the other, AutoFixture supports them both.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=20eacbdc-fcb2-4dc0-9024-c3735cb762a3" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,20eacbdc-fcb2-4dc0-9024-c3735cb762a3.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=7f180a32-fc1d-4322-a295-64cfc6996e80</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,7f180a32-fc1d-4322-a295-64cfc6996e80.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,7f180a32-fc1d-4322-a295-64cfc6996e80.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=7f180a32-fc1d-4322-a295-64cfc6996e80</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
About a year ago, one of my readers <a href="http://blogs.msdn.com/ploeh/archive/2008/05/01/DeclarativeUseOfCustomSecurityTokenParameters.aspx#8575741">asked
me about how to make custom tokens work over TPC</a> in WCF. Here's the question again:
</p>
        <p>
"i'm trying to implement the CustomToken over tcp. The original used the SymmetricSecurityBindingElement
and the transport http, this works fine, but when i change URI's and and the transport,
it gives an error saying: 
</p>
        <p>
"Binding 'CustomBinding' doesn't support creating any channel types. This often indicates
that the BindingElements in a CustomBinding have been stacked incorrectly or in the
wrong order. A Transport is required at the bottom of the stack. The recommended order
for BindingElements is: TransactionFlow, ReliableSession, Security, CompositeDuplex,
OneWay, StreamSecurity, MessageEncoding, Transport." 
</p>
        <p>
As it turns out, this seems to be a general issue with more transports than just TCP
– at least, I've seen the exact same behavior for the Named Pipes transport. 
</p>
        <p>
When I originally received the question, it seemed that no-one knew the answer, and
neither did I. Now, about a year later, I've managed to find a solution, and it's
really simple. 
</p>
        <p>
If you build up your CustomBinding in code, all you need to do is set the <a href="http://msdn.microsoft.com/en-us/library/microsoft.servicebus.channels.connectionorientedtransportbindingelement.transfermode.aspx">TransferMode</a> property
to <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.transfermode.aspx">Streamed</a>: 
</p>
        <p>
          <!--
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  pipeTransport = \cf1 new\cf0  \cf4 NamedPipeTransportBindingElement\cf0 ();\par ??pipeTransport.TransferMode = \cf4 TransferMode\cf0 .Streamed;}
-->
        </p>
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> pipeTransport
= <span style="color: blue">new</span><span style="color: #2b91af">NamedPipeTransportBindingElement</span>();</pre>
          <pre style="margin: 0px">pipeTransport.TransferMode = <span style="color: #2b91af">TransferMode</span>.Streamed;</pre>
        </div>
        <p>
In this example, I'm setting the property on a Named Pipe transport, but you can do
exactly the same with a TCP transport.
</p>
        <p>
Although I wasn't able to find any documentation to that effect, experimentation seems
to indicate that you can also set the property in a .config file (at least, it works
on my computer):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &lt;\cf3 namedPipeTransport\cf1  \cf4 transferMode\cf1 =\cf0 "\cf1 Streamed\cf0 "\cf1  /&gt;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">&lt;</span>
            <span style="color: #a31515">namedPipeTransport</span>
            <span style="color: blue">
            </span>
            <span style="color: red">transferMode</span>
            <span style="color: blue">=</span>"<span style="color: blue">Streamed</span>"<span style="color: blue"> /&gt;</span></pre>
        </div>
        <p>
I will not claim that I fully understand this fix/workaround, or that it applies in
every situation, but I hope that it might prove helpful to some of my readers some
day.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7f180a32-fc1d-4322-a295-64cfc6996e80" />
      </body>
      <title>Custom Tokens Over Non-HTTP Transports</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,7f180a32-fc1d-4322-a295-64cfc6996e80.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/22/CustomTokensOverNonHTTPTransports.aspx</link>
      <pubDate>Mon, 22 Jun 2009 19:48:42 GMT</pubDate>
      <description>&lt;p&gt;
About a year ago, one of my readers &lt;a href="http://blogs.msdn.com/ploeh/archive/2008/05/01/DeclarativeUseOfCustomSecurityTokenParameters.aspx#8575741"&gt;asked
me about how to make custom tokens work over TPC&lt;/a&gt; in WCF. Here's the question again:
&lt;/p&gt;
&lt;p&gt;
"i'm trying to implement the CustomToken over tcp. The original used the SymmetricSecurityBindingElement
and the transport http, this works fine, but when i change URI's and and the transport,
it gives an error saying: 
&lt;p&gt;
"Binding 'CustomBinding' doesn't support creating any channel types. This often indicates
that the BindingElements in a CustomBinding have been stacked incorrectly or in the
wrong order. A Transport is required at the bottom of the stack. The recommended order
for BindingElements is: TransactionFlow, ReliableSession, Security, CompositeDuplex,
OneWay, StreamSecurity, MessageEncoding, Transport." 
&lt;p&gt;
As it turns out, this seems to be a general issue with more transports than just TCP
– at least, I've seen the exact same behavior for the Named Pipes transport. 
&lt;p&gt;
When I originally received the question, it seemed that no-one knew the answer, and
neither did I. Now, about a year later, I've managed to find a solution, and it's
really simple. 
&lt;p&gt;
If you build up your CustomBinding in code, all you need to do is set the &lt;a href="http://msdn.microsoft.com/en-us/library/microsoft.servicebus.channels.connectionorientedtransportbindingelement.transfermode.aspx"&gt;TransferMode&lt;/a&gt; property
to &lt;a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.transfermode.aspx"&gt;Streamed&lt;/a&gt;: 
&lt;p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof1252\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  pipeTransport = \cf1 new\cf0  \cf4 NamedPipeTransportBindingElement\cf0 ();\par ??pipeTransport.TransferMode = \cf4 TransferMode\cf0 .Streamed;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; pipeTransport
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NamedPipeTransportBindingElement&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;pipeTransport.TransferMode = &lt;span style="color: #2b91af"&gt;TransferMode&lt;/span&gt;.Streamed;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this example, I'm setting the property on a Named Pipe transport, but you can do
exactly the same with a TCP transport.
&lt;/p&gt;
&lt;p&gt;
Although I wasn't able to find any documentation to that effect, experimentation seems
to indicate that you can also set the property in a .config file (at least, it works
on my computer):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red163\green21\blue21;\red255\green0\blue0;\red0\green0\blue0;}??\fs20 \cf1 &amp;lt;\cf3 namedPipeTransport\cf1  \cf4 transferMode\cf1 =\cf0 "\cf1 Streamed\cf0 "\cf1  /&amp;gt;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;lt;&lt;/span&gt;&lt;span style="color: #a31515"&gt;namedPipeTransport&lt;/span&gt;&lt;span style="color: blue"&gt; &lt;/span&gt;&lt;span style="color: red"&gt;transferMode&lt;/span&gt;&lt;span style="color: blue"&gt;=&lt;/span&gt;"&lt;span style="color: blue"&gt;Streamed&lt;/span&gt;"&lt;span style="color: blue"&gt; /&amp;gt;&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I will not claim that I fully understand this fix/workaround, or that it applies in
every situation, but I hope that it might prove helpful to some of my readers some
day.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7f180a32-fc1d-4322-a295-64cfc6996e80" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,7f180a32-fc1d-4322-a295-64cfc6996e80.aspx</comments>
      <category>Services</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=bc05b900-0198-4401-9281-0661cce23f47</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,bc05b900-0198-4401-9281-0661cce23f47.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,bc05b900-0198-4401-9281-0661cce23f47.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=bc05b900-0198-4401-9281-0661cce23f47</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It was only earlier this week that I released <a href="http://autofixture.codeplex.com/">AutoFixture</a> .8.2,
but now I'm releasing version .8.3 – not that there was anything wrong with .8.2 (that
I know of), but I had some time to implement new features, and I wanted to properly
release those.
</p>
        <p>
In the future I will blog about these new features (along with all the other AutoFixture
features I haven't introduced yet).
</p>
        <p>
Get it at the <a href="http://autofixture.codeplex.com/">AutoFixture CodePlex site</a> as
usual.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=bc05b900-0198-4401-9281-0661cce23f47" />
      </body>
      <title>AutoFixture .8.3 Released</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,bc05b900-0198-4401-9281-0661cce23f47.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/20/AutoFixture83Released.aspx</link>
      <pubDate>Sat, 20 Jun 2009 08:34:30 GMT</pubDate>
      <description>&lt;p&gt;
It was only earlier this week that I released &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; .8.2,
but now I'm releasing version .8.3 – not that there was anything wrong with .8.2 (that
I know of), but I had some time to implement new features, and I wanted to properly
release those.
&lt;/p&gt;
&lt;p&gt;
In the future I will blog about these new features (along with all the other AutoFixture
features I haven't introduced yet).
&lt;/p&gt;
&lt;p&gt;
Get it at the &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture CodePlex site&lt;/a&gt; as
usual.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=bc05b900-0198-4401-9281-0661cce23f47" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,bc05b900-0198-4401-9281-0661cce23f47.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=52f0daf5-7fa9-4469-9bd7-693cc6f013ba</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,52f0daf5-7fa9-4469-9bd7-693cc6f013ba.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,52f0daf5-7fa9-4469-9bd7-693cc6f013ba.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=52f0daf5-7fa9-4469-9bd7-693cc6f013ba</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Yesterday I created a new release (.8.2) of <a href="http://autofixture.codeplex.com/">AutoFixture</a>;
this time with a new feature that I recently discovered that I needed, and about which
I will blog later.
</p>
        <p>
There are no breaking changes and no known bugs.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=52f0daf5-7fa9-4469-9bd7-693cc6f013ba" />
      </body>
      <title>AutoFixture .8.2 Released</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,52f0daf5-7fa9-4469-9bd7-693cc6f013ba.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/18/AutoFixture82Released.aspx</link>
      <pubDate>Thu, 18 Jun 2009 19:11:39 GMT</pubDate>
      <description>&lt;p&gt;
Yesterday I created a new release (.8.2) of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;;
this time with a new feature that I recently discovered that I needed, and about which
I will blog later.
&lt;/p&gt;
&lt;p&gt;
There are no breaking changes and no known bugs.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=52f0daf5-7fa9-4469-9bd7-693cc6f013ba" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,52f0daf5-7fa9-4469-9bd7-693cc6f013ba.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=7ed1ecda-73ae-47a4-8be2-0bd276cbce50</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,7ed1ecda-73ae-47a4-8be2-0bd276cbce50.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,7ed1ecda-73ae-47a4-8be2-0bd276cbce50.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=7ed1ecda-73ae-47a4-8be2-0bd276cbce50</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Previously, we saw how you can <a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx">set
property values while building</a><a href="http://blogs.msdn.com/ploeh/archive/2008/11/17/anonymous-variables.aspx">anonymous
variables</a> with <a href="http://autofixture.codeplex.com/">AutoFixture</a>. While
I insinuated that I consider this a somewhat atypical scenario, we can now safely
venture forth to the truly exotic :)
</p>
        <p>
Imagine that you want to build an anonymous instance of a type that requires you to
call a certain method before you can start assigning properties. It's difficult to
come up with a reasonable example of this, but although I consider it quite bad design,
I've seen interfaces that include an Initialize method that must be called before
any other member. In our example, let's call this interface IBadDesign.
</p>
        <p>
Let's say that we have a class called SomeImp that implements IBadDesign. Here's the
relevant part of the class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 #region\cf0  IBadDesign Members\par ??\par ??\cf1 public\cf0  \cf1 string\cf0  Message\par ??\{\par ??    \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .message; \}\par ??    \cf1 set\par ??\cf0     \{\par ??        \cf1 if\cf0  (\cf1 this\cf0 .mc == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 InvalidOperationException\cf0 (\cf5 "..."\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .message = \cf1 value\cf0 ;\par ??        \cf1 this\cf0 .transformedMessage = \cf1 this\cf0 .mc.DoStuff(\cf1 value\cf0 );\par ??    \}\par ??\}\par ??\par ??\cf1 public\cf0  \cf1 void\cf0  Initialize(\cf4 MyClass\cf0  mc)\par ??\{\par ??    \cf1 this\cf0 .mc = mc;\par ??\}\par ??\par ??\cf1 #endregion}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">#region</span> IBadDesign
Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">string</span> Message</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">get</span> { <span style="color: blue">return</span><span style="color: blue">this</span>.message;
}</pre>
          <pre style="margin: 0px">    <span style="color: blue">set</span></pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (<span style="color: blue">this</span>.mc
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">"..."</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.message
= <span style="color: blue">value</span>;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.transformedMessage
= <span style="color: blue">this</span>.mc.DoStuff(<span style="color: blue">value</span>);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> Initialize(<span style="color: #2b91af">MyClass</span> mc)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.mc
= mc;</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">#endregion</span>
          </pre>
        </div>
        <p>
This is a rather ridiculous example, but I couldn't think of a better one. The main
point here is that given a brand-new instance of SomeImp, this usage is invalid:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red163\green21\blue21;}??\fs20 something.Message = \cf3 "Ploeh"\cf0 ;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">something.Message = <span style="color: #a31515">"Ploeh"</span>;</pre>
        </div>
        <p>
While the above code snippet will throw an InvalidOperationException, this will work:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 something.Initialize(\cf3 new\cf0  \cf4 MyClass\cf0 ());\par ??something.Message = \cf5 "Ploeh"\cf0 ;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">something.Initialize(<span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>());</pre>
          <pre style="margin: 0px">something.Message = <span style="color: #a31515">"Ploeh"</span>;</pre>
        </div>
        <p>
The problem is that by default, AutoFixture ignores methods and only assigns properties,
which means that this is also going to throw:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  imp = fixture.CreateAnonymous&lt;\cf4 SomeImp\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> imp
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">SomeImp</span>&gt;();</pre>
        </div>
        <p>
As we saw with properties, we can use the Build method to customize how the type is
being created. Properties can be set with the With method, while methods can be invoked
with the Do method, so this is all it takes:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  imp = fixture.Build&lt;\cf4 SomeImp\cf0 &gt;()\par ??    .Do(s =&gt; s.Initialize(\cf1 new\cf0  \cf4 MyClass\cf0 ()))\par ??    .CreateAnonymous();    }
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> imp
= fixture.Build&lt;<span style="color: #2b91af">SomeImp</span>&gt;()</pre>
          <pre style="margin: 0px">    .Do(s =&gt; s.Initialize(<span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>()))</pre>
          <pre style="margin: 0px">    .CreateAnonymous();    </pre>
        </div>
        <p>
We don't have to explicitly set the Message property, as AutoFixture is going to do
this automatically, and all implicit assignments happen after explicit actions defined
by With or Do (and in case you were wondering, you can mix With and Do, and ObjectBuilder&lt;T&gt;
will preserve the ordering).
</p>
        <p>
In most cases, having to use the Do method probably constitutes a design smell of
the <a href="http://xunitpatterns.com/SUT.html">SUT</a>, but the method is there if
you need it.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7ed1ecda-73ae-47a4-8be2-0bd276cbce50" />
      </body>
      <title>Calling Methods While Building Anonymous Variables With AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,7ed1ecda-73ae-47a4-8be2-0bd276cbce50.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/09/CallingMethodsWhileBuildingAnonymousVariablesWithAutoFixture.aspx</link>
      <pubDate>Tue, 09 Jun 2009 17:50:54 GMT</pubDate>
      <description>&lt;p&gt;
Previously, we saw how you can &lt;a href="http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx"&gt;set
property values while building&lt;/a&gt; &lt;a href="http://blogs.msdn.com/ploeh/archive/2008/11/17/anonymous-variables.aspx"&gt;anonymous
variables&lt;/a&gt; with &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;. While
I insinuated that I consider this a somewhat atypical scenario, we can now safely
venture forth to the truly exotic :)
&lt;/p&gt;
&lt;p&gt;
Imagine that you want to build an anonymous instance of a type that requires you to
call a certain method before you can start assigning properties. It's difficult to
come up with a reasonable example of this, but although I consider it quite bad design,
I've seen interfaces that include an Initialize method that must be called before
any other member. In our example, let's call this interface IBadDesign.
&lt;/p&gt;
&lt;p&gt;
Let's say that we have a class called SomeImp that implements IBadDesign. Here's the
relevant part of the class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 #region\cf0  IBadDesign Members\par ??\par ??\cf1 public\cf0  \cf1 string\cf0  Message\par ??\{\par ??    \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .message; \}\par ??    \cf1 set\par ??\cf0     \{\par ??        \cf1 if\cf0  (\cf1 this\cf0 .mc == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 InvalidOperationException\cf0 (\cf5 "..."\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .message = \cf1 value\cf0 ;\par ??        \cf1 this\cf0 .transformedMessage = \cf1 this\cf0 .mc.DoStuff(\cf1 value\cf0 );\par ??    \}\par ??\}\par ??\par ??\cf1 public\cf0  \cf1 void\cf0  Initialize(\cf4 MyClass\cf0  mc)\par ??\{\par ??    \cf1 this\cf0 .mc = mc;\par ??\}\par ??\par ??\cf1 #endregion}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;#region&lt;/span&gt; IBadDesign
Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; Message&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.message;
}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;set&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (&lt;span style="color: blue"&gt;this&lt;/span&gt;.mc
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;InvalidOperationException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"..."&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.message
= &lt;span style="color: blue"&gt;value&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.transformedMessage
= &lt;span style="color: blue"&gt;this&lt;/span&gt;.mc.DoStuff(&lt;span style="color: blue"&gt;value&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Initialize(&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt; mc)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.mc
= mc;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;#endregion&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is a rather ridiculous example, but I couldn't think of a better one. The main
point here is that given a brand-new instance of SomeImp, this usage is invalid:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red163\green21\blue21;}??\fs20 something.Message = \cf3 "Ploeh"\cf0 ;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;something.Message = &lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
While the above code snippet will throw an InvalidOperationException, this will work:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 something.Initialize(\cf3 new\cf0  \cf4 MyClass\cf0 ());\par ??something.Message = \cf5 "Ploeh"\cf0 ;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;something.Initialize(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;something.Message = &lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The problem is that by default, AutoFixture ignores methods and only assigns properties,
which means that this is also going to throw:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  imp = fixture.CreateAnonymous&amp;lt;\cf4 SomeImp\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; imp
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;SomeImp&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
As we saw with properties, we can use the Build method to customize how the type is
being created. Properties can be set with the With method, while methods can be invoked
with the Do method, so this is all it takes:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  imp = fixture.Build&amp;lt;\cf4 SomeImp\cf0 &amp;gt;()\par ??    .Do(s =&amp;gt; s.Initialize(\cf1 new\cf0  \cf4 MyClass\cf0 ()))\par ??    .CreateAnonymous();    }
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; imp
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;SomeImp&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Do(s =&amp;gt; s.Initialize(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;()))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We don't have to explicitly set the Message property, as AutoFixture is going to do
this automatically, and all implicit assignments happen after explicit actions defined
by With or Do (and in case you were wondering, you can mix With and Do, and ObjectBuilder&amp;lt;T&amp;gt;
will preserve the ordering).
&lt;/p&gt;
&lt;p&gt;
In most cases, having to use the Do method probably constitutes a design smell of
the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;, but the method is there if
you need it.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7ed1ecda-73ae-47a4-8be2-0bd276cbce50" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,7ed1ecda-73ae-47a4-8be2-0bd276cbce50.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=e32f1f0a-6fc2-4397-8e06-4fe6035487bb</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,e32f1f0a-6fc2-4397-8e06-4fe6035487bb.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,e32f1f0a-6fc2-4397-8e06-4fe6035487bb.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=e32f1f0a-6fc2-4397-8e06-4fe6035487bb</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Lately, several people have implied to me that I should consider start using <a href="http://twitter.com">Twitter</a>,
so <a href="http://twitter.com/ploeh">here I am</a>, with only a vague idea about
what to do with it…
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=e32f1f0a-6fc2-4397-8e06-4fe6035487bb" />
      </body>
      <title>Tweet</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,e32f1f0a-6fc2-4397-8e06-4fe6035487bb.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/05/Tweet.aspx</link>
      <pubDate>Fri, 05 Jun 2009 19:12:49 GMT</pubDate>
      <description>&lt;p&gt;
Lately, several people have implied to me that I should consider start using &lt;a href="http://twitter.com"&gt;Twitter&lt;/a&gt;,
so &lt;a href="http://twitter.com/ploeh"&gt;here I am&lt;/a&gt;, with only a vague idea about
what to do with it…
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=e32f1f0a-6fc2-4397-8e06-4fe6035487bb" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,e32f1f0a-6fc2-4397-8e06-4fe6035487bb.aspx</comments>
      <category>Miscellaneous</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When I talk with people about TDD and unit testing, the discussion often moves into
the area of Testability – that is, the software's susceptibility to unit testing.
A couple of years back, <a href="http://weblogs.asp.net/rosherove/default.aspx">Roy</a> even
discussed the seemingly <a href="http://weblogs.asp.net/rosherove/archive/2007/02/25/why-you-should-think-about-ootp-object-oriented-testable-programming.aspx">opposable
forces of Object-Oriented Design and Testability</a>.
</p>
        <p>
Lately, it has been occurring to me that there really isn't any conflict. Encapsulation
is important because it manifests expert knowledge so that other developers can effectively
leverage that knowledge, and it does so in a way that minimizes misuse.
</p>
        <p>
However, too much encapsulation goes against the Open/Closed Principle (that states
that objects should be open for extension, but closed for modification). From a Testability
perspective, the Open/Closed Principle pulls object-oriented design in the desired
direction. Equivalently, done correctly, making your API Testable is simply opening
it up for extensibility.
</p>
        <p>
As an example, consider a simple <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">WPF
ViewModel</a> class called MainWindowViewModel. This class has an <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand</a> property
that, when invoked, should show a message box. Showing a message box is good example
of breaking testability, because if the <a href="http://xunitpatterns.com/SUT.html">SUT</a> were
to show a message box, it would be very hard to automatically verify and we wouldn't
have fully automated tests.
</p>
        <p>
For this reason, we need to introduce an abstraction that basically models an action
with a string as input. <a href="http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx">Although
we could define an interface for that, an Action&lt;string&gt; fits the bill perfectly</a>.
</p>
        <p>
To enable that feature, I decide to use Constructor Injection to inject that abstraction
into the MainWindowViewModel class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  MainWindowViewModel(\cf4 Action\cf0 &lt;\cf1 string\cf0 &gt; notify)\par ??\{\par ??    \cf1 this\cf0 .ButtonCommand = \cf1 new\cf0  \cf4 RelayCommand\cf0 (p =&gt; \par ??    \{ notify(\cf5 "Button was clicked!"\cf0 ); \});\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> MainWindowViewModel(<span style="color: #2b91af">Action</span>&lt;<span style="color: blue">string</span>&gt;
notify)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.ButtonCommand
= <span style="color: blue">new</span><span style="color: #2b91af">RelayCommand</span>(p
=&gt; </pre>
          <pre style="margin: 0px">    { notify(<span style="color: #a31515">"Button
was clicked!"</span>); });</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
When I recently did that at a public talk I gave, one member of the audience initially
reacted by assuming that I was now introducing test-specific code into my SUT, but
that's not the case.
</p>
        <p>
What I'm really doing here is opening the MainWindowViewModel class for extensibility.
It can still be used with message boxes:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  vm = \cf1 new\cf0  \cf4 MainWindowViewModel\cf0 (s =&gt; \cf4 MessageBox\cf0 .Show(s));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> vm
= <span style="color: blue">new</span><span style="color: #2b91af">MainWindowViewModel</span>(s
=&gt; <span style="color: #2b91af">MessageBox</span>.Show(s));</pre>
        </div>
        <p>
but now we also have the option of notifying by sending off an email; writing to a
database; or whatever else we can think of.
</p>
        <p>
It just so happens that one of the things we can do instead of showing a message box,
is unit testing by passing in a <a href="http://xunitpatterns.com/Test%20Double.html">Test
Double</a>.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  mockNotify = \par ??    \cf5 MockRepository\cf0 .GenerateMock&lt;\cf5 Action\cf0 &lt;\cf3 string\cf0 &gt;&gt;();\par ??mockNotify.Expect(a =&gt; a(\cf6 "Button was clicked!"\cf0 ));\par ??\par ??\cf3 var\cf0  sut = \cf3 new\cf0  \cf5 MainWindowViewModel\cf0 (mockNotify);\par ??\cf1 // Exercise system\par ??\cf0 sut.ButtonCommand.Execute(\cf3 new\cf0  \cf3 object\cf0 ());\par ??\cf1 // Verify outcome\par ??\cf0 mockNotify.VerifyAllExpectations();\par ??\cf1 // Teardown}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: green">//
Fixture setup</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mockNotify
= </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">Action</span>&lt;<span style="color: blue">string</span>&gt;&gt;();</pre>
          <pre style="margin: 0px">mockNotify.Expect(a =&gt; a(<span style="color: #a31515">"Button
was clicked!"</span>));</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MainWindowViewModel</span>(mockNotify);</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Exercise system</span>
          </pre>
          <pre style="margin: 0px">sut.ButtonCommand.Execute(<span style="color: blue">new</span><span style="color: blue">object</span>());</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Verify outcome</span>
          </pre>
          <pre style="margin: 0px">mockNotify.VerifyAllExpectations();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Teardown</span>
          </pre>
        </div>
        <p>
Once again, TDD has lead to better design. In this case it prompted me to open the
class for extensibility. There really isn't a need for Testability as a specific concept;
the Open/Closed Principle should be enough to drive us in the right direction.
</p>
        <p>
Pragmatically, that's not the case, so we use TDD to drive us towards the Open/Closed
Principle, but I think it's important to note that we are not only doing this to enable
testing: We are creating a better and more flexible API at the same time.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c" />
      </body>
      <title>Testability Is Really The Open/Closed Principle</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/05/TestabilityIsReallyTheOpenClosedPrinciple.aspx</link>
      <pubDate>Fri, 05 Jun 2009 07:56:19 GMT</pubDate>
      <description>&lt;p&gt;
When I talk with people about TDD and unit testing, the discussion often moves into
the area of Testability – that is, the software's susceptibility to unit testing.
A couple of years back, &lt;a href="http://weblogs.asp.net/rosherove/default.aspx"&gt;Roy&lt;/a&gt; even
discussed the seemingly &lt;a href="http://weblogs.asp.net/rosherove/archive/2007/02/25/why-you-should-think-about-ootp-object-oriented-testable-programming.aspx"&gt;opposable
forces of Object-Oriented Design and Testability&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Lately, it has been occurring to me that there really isn't any conflict. Encapsulation
is important because it manifests expert knowledge so that other developers can effectively
leverage that knowledge, and it does so in a way that minimizes misuse.
&lt;/p&gt;
&lt;p&gt;
However, too much encapsulation goes against the Open/Closed Principle (that states
that objects should be open for extension, but closed for modification). From a Testability
perspective, the Open/Closed Principle pulls object-oriented design in the desired
direction. Equivalently, done correctly, making your API Testable is simply opening
it up for extensibility.
&lt;/p&gt;
&lt;p&gt;
As an example, consider a simple &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;WPF
ViewModel&lt;/a&gt; class called MainWindowViewModel. This class has an &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx"&gt;ICommand&lt;/a&gt; property
that, when invoked, should show a message box. Showing a message box is good example
of breaking testability, because if the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt; were
to show a message box, it would be very hard to automatically verify and we wouldn't
have fully automated tests.
&lt;/p&gt;
&lt;p&gt;
For this reason, we need to introduce an abstraction that basically models an action
with a string as input. &lt;a href="http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx"&gt;Although
we could define an interface for that, an Action&amp;lt;string&amp;gt; fits the bill perfectly&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
To enable that feature, I decide to use Constructor Injection to inject that abstraction
into the MainWindowViewModel class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  MainWindowViewModel(\cf4 Action\cf0 &amp;lt;\cf1 string\cf0 &amp;gt; notify)\par ??\{\par ??    \cf1 this\cf0 .ButtonCommand = \cf1 new\cf0  \cf4 RelayCommand\cf0 (p =&amp;gt; \par ??    \{ notify(\cf5 "Button was clicked!"\cf0 ); \});\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; MainWindowViewModel(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;
notify)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ButtonCommand
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;RelayCommand&lt;/span&gt;(p
=&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { notify(&lt;span style="color: #a31515"&gt;"Button
was clicked!"&lt;/span&gt;); });&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
When I recently did that at a public talk I gave, one member of the audience initially
reacted by assuming that I was now introducing test-specific code into my SUT, but
that's not the case.
&lt;/p&gt;
&lt;p&gt;
What I'm really doing here is opening the MainWindowViewModel class for extensibility.
It can still be used with message boxes:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  vm = \cf1 new\cf0  \cf4 MainWindowViewModel\cf0 (s =&amp;gt; \cf4 MessageBox\cf0 .Show(s));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; vm
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MainWindowViewModel&lt;/span&gt;(s
=&amp;gt; &lt;span style="color: #2b91af"&gt;MessageBox&lt;/span&gt;.Show(s));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
but now we also have the option of notifying by sending off an email; writing to a
database; or whatever else we can think of.
&lt;/p&gt;
&lt;p&gt;
It just so happens that one of the things we can do instead of showing a message box,
is unit testing by passing in a &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test
Double&lt;/a&gt;.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  mockNotify = \par ??    \cf5 MockRepository\cf0 .GenerateMock&amp;lt;\cf5 Action\cf0 &amp;lt;\cf3 string\cf0 &amp;gt;&amp;gt;();\par ??mockNotify.Expect(a =&amp;gt; a(\cf6 "Button was clicked!"\cf0 ));\par ??\par ??\cf3 var\cf0  sut = \cf3 new\cf0  \cf5 MainWindowViewModel\cf0 (mockNotify);\par ??\cf1 // Exercise system\par ??\cf0 sut.ButtonCommand.Execute(\cf3 new\cf0  \cf3 object\cf0 ());\par ??\cf1 // Verify outcome\par ??\cf0 mockNotify.VerifyAllExpectations();\par ??\cf1 // Teardown}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mockNotify
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mockNotify.Expect(a =&amp;gt; a(&lt;span style="color: #a31515"&gt;"Button
was clicked!"&lt;/span&gt;));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MainWindowViewModel&lt;/span&gt;(mockNotify);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.ButtonCommand.Execute(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: blue"&gt;object&lt;/span&gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mockNotify.VerifyAllExpectations();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Once again, TDD has lead to better design. In this case it prompted me to open the
class for extensibility. There really isn't a need for Testability as a specific concept;
the Open/Closed Principle should be enough to drive us in the right direction.
&lt;/p&gt;
&lt;p&gt;
Pragmatically, that's not the case, so we use TDD to drive us towards the Open/Closed
Principle, but I think it's important to note that we are not only doing this to enable
testing: We are creating a better and more flexible API at the same time.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</comments>
      <category>Software Design</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=54b09f14-e03f-4081-b493-5fe3f95cc47d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,54b09f14-e03f-4081-b493-5fe3f95cc47d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,54b09f14-e03f-4081-b493-5fe3f95cc47d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=54b09f14-e03f-4081-b493-5fe3f95cc47d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
To make it a bit easier to get started with <a href="http://autofixture.codeplex.com/">AutoFixture</a> without
having to trawl through all my blog posts, I've added a <a href="http://autofixture.codeplex.com/Wiki/View.aspx?title=CheatSheet">Cheat
Sheet</a> over at the AutoFixture CodePlex site.
</p>
        <p>
As I add more posts on AutoFixture, I'll update the Cheat Sheet with the essentials.
Please let me know if you think something's missing.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=54b09f14-e03f-4081-b493-5fe3f95cc47d" />
      </body>
      <title>AutoFixture Cheat Sheet</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,54b09f14-e03f-4081-b493-5fe3f95cc47d.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/04/AutoFixtureCheatSheet.aspx</link>
      <pubDate>Thu, 04 Jun 2009 21:15:08 GMT</pubDate>
      <description>&lt;p&gt;
To make it a bit easier to get started with &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; without
having to trawl through all my blog posts, I've added a &lt;a href="http://autofixture.codeplex.com/Wiki/View.aspx?title=CheatSheet"&gt;Cheat
Sheet&lt;/a&gt; over at the AutoFixture CodePlex site.
&lt;/p&gt;
&lt;p&gt;
As I add more posts on AutoFixture, I'll update the Cheat Sheet with the essentials.
Please let me know if you think something's missing.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=54b09f14-e03f-4081-b493-5fe3f95cc47d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,54b09f14-e03f-4081-b493-5fe3f95cc47d.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=a5013fc1-44d8-4930-aa7d-77aee8d60db6</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,a5013fc1-44d8-4930-aa7d-77aee8d60db6.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,a5013fc1-44d8-4930-aa7d-77aee8d60db6.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=a5013fc1-44d8-4930-aa7d-77aee8d60db6</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my previous post I described <a href="http://blog.ploeh.dk/2009/05/26/TheAutoFixtureBuilder.aspx">how
the Build method can be used to customize how a single anonymous variable is created</a>.
</p>
        <p>
A common customization is to set a property value during creation. In most cases,
this can simply be done <em>after</em> the anonymous variable has been created (so
the following is not an AutoFixture customization):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClass\cf0 &gt;();\par ??mc.MyText = \cf5 "Ploeh"\cf0 ;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">mc.MyText = <span style="color: #a31515">"Ploeh"</span>;</pre>
        </div>
        <p>
By default, <a href="http://autofixture.codeplex.com/">AutoFixture</a> assigns anonymous
values to all writable properties, but since they are writable, you can always explicitly
give them different values if you care.
</p>
        <p>
However, there are situations when a property is writable, but can't take just any
value of its type. Sometimes this is a sign that you should reconsider your API, as
I've <a href="http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx">previously
described</a>, but it may also be a legitimate situation.
</p>
        <p>
Consider a Filter class that has Min and Max properties. To be semantically correct,
the Min property must be less than or equal to the Max property. Each property is
implemented like this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 int\cf0  Min\par ??\{\par ??    \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .min; \}\par ??    \cf1 set\par ??\cf0     \{\par ??        \cf1 if\cf0  (\cf1 value\cf0  &gt; \cf1 this\cf0 .Max)\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "value"\cf0 );\par ??        \}\par ??        \cf1 this\cf0 .min = \cf1 value\cf0 ;\par ??    \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">int</span> Min</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">get</span> { <span style="color: blue">return</span><span style="color: blue">this</span>.min;
}</pre>
          <pre style="margin: 0px">    <span style="color: blue">set</span></pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (<span style="color: blue">value</span> &gt; <span style="color: blue">this</span>.Max)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentOutOfRangeException</span>(<span style="color: #a31515">"value"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.min
= <span style="color: blue">value</span>;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
When you ask AutoFixture to create an instance of the Filter class, it will throw
an exception because it's attempting to set the Min property after the Max property,
and the <a href="http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture.aspx">default
algorithm for numbers</a> is to return numbers in an increasing sequence. (In this
example, the Min property is being assigned a value <em>after</em> the Max property,
but AutoFixture has no contract that states that the order in which properties are
assigned is guaranteed.) In other words, this throws an exception:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  f = fixture.CreateAnonymous&lt;\cf4 Filter\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> f
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Filter</span>&gt;();</pre>
        </div>
        <p>
To solve this problem, we will have to customize the assignment of the Min and Max
properties, <em>before</em> we ask AutoFixture to create an instance of the Filter
class. Here's how to do that:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 int\cf0  min = fixture.CreateAnonymous&lt;\cf1 int\cf0 &gt;();\par ??\cf1 int\cf0  max = min + 1;\par ??\cf1 var\cf0  f = fixture.Build&lt;\cf4 Filter\cf0 &gt;()\par ??    .With(s =&gt; s.Max, max)\par ??    .With(s =&gt; s.Min, min)\par ??    .CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">int</span> min
= fixture.CreateAnonymous&lt;<span style="color: blue">int</span>&gt;();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">int</span> max
= min + 1;</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> f =
fixture.Build&lt;<span style="color: #2b91af">Filter</span>&gt;()</pre>
          <pre style="margin: 0px">    .With(s =&gt; s.Max, max)</pre>
          <pre style="margin: 0px">    .With(s =&gt; s.Min, min)</pre>
          <pre style="margin: 0px">    .CreateAnonymous();</pre>
        </div>
        <p>
The With method lets you specify an expression that identifies a property, as well
as the value that should be assigned to that property. When you do that, AutoFixture
will never attempt to assign an anonymous value to that property, but will instead
use the value you specified.
</p>
        <p>
In most cases, just creating a truly anonymous instance and subsequently explicitly
assigning any significant values is easier, but using the Build method with one or
more calls to the With method gives you the power to override any property assignments
before the instance is created.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a5013fc1-44d8-4930-aa7d-77aee8d60db6" />
      </body>
      <title>Setting Property Values While Building Anonymous Variables With AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,a5013fc1-44d8-4930-aa7d-77aee8d60db6.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/01/SettingPropertyValuesWhileBuildingAnonymousVariablesWithAutoFixture.aspx</link>
      <pubDate>Mon, 01 Jun 2009 12:35:18 GMT</pubDate>
      <description>&lt;p&gt;
In my previous post I described &lt;a href="http://blog.ploeh.dk/2009/05/26/TheAutoFixtureBuilder.aspx"&gt;how
the Build method can be used to customize how a single anonymous variable is created&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
A common customization is to set a property value during creation. In most cases,
this can simply be done &lt;em&gt;after&lt;/em&gt; the anonymous variable has been created (so
the following is not an AutoFixture customization):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClass\cf0 &amp;gt;();\par ??mc.MyText = \cf5 "Ploeh"\cf0 ;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mc.MyText = &lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
By default, &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; assigns anonymous
values to all writable properties, but since they are writable, you can always explicitly
give them different values if you care.
&lt;/p&gt;
&lt;p&gt;
However, there are situations when a property is writable, but can't take just any
value of its type. Sometimes this is a sign that you should reconsider your API, as
I've &lt;a href="http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx"&gt;previously
described&lt;/a&gt;, but it may also be a legitimate situation.
&lt;/p&gt;
&lt;p&gt;
Consider a Filter class that has Min and Max properties. To be semantically correct,
the Min property must be less than or equal to the Max property. Each property is
implemented like this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 int\cf0  Min\par ??\{\par ??    \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .min; \}\par ??    \cf1 set\par ??\cf0     \{\par ??        \cf1 if\cf0  (\cf1 value\cf0  &amp;gt; \cf1 this\cf0 .Max)\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "value"\cf0 );\par ??        \}\par ??        \cf1 this\cf0 .min = \cf1 value\cf0 ;\par ??    \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; Min&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.min;
}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;set&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (&lt;span style="color: blue"&gt;value&lt;/span&gt; &amp;gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Max)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentOutOfRangeException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"value"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.min
= &lt;span style="color: blue"&gt;value&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
When you ask AutoFixture to create an instance of the Filter class, it will throw
an exception because it's attempting to set the Min property after the Max property,
and the &lt;a href="http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture.aspx"&gt;default
algorithm for numbers&lt;/a&gt; is to return numbers in an increasing sequence. (In this
example, the Min property is being assigned a value &lt;em&gt;after&lt;/em&gt; the Max property,
but AutoFixture has no contract that states that the order in which properties are
assigned is guaranteed.) In other words, this throws an exception:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  f = fixture.CreateAnonymous&amp;lt;\cf4 Filter\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; f
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Filter&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
To solve this problem, we will have to customize the assignment of the Min and Max
properties, &lt;em&gt;before&lt;/em&gt; we ask AutoFixture to create an instance of the Filter
class. Here's how to do that:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 int\cf0  min = fixture.CreateAnonymous&amp;lt;\cf1 int\cf0 &amp;gt;();\par ??\cf1 int\cf0  max = min + 1;\par ??\cf1 var\cf0  f = fixture.Build&amp;lt;\cf4 Filter\cf0 &amp;gt;()\par ??    .With(s =&amp;gt; s.Max, max)\par ??    .With(s =&amp;gt; s.Min, min)\par ??    .CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;int&lt;/span&gt; min
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;int&lt;/span&gt; max
= min + 1;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; f =
fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;Filter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(s =&amp;gt; s.Max, max)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .With(s =&amp;gt; s.Min, min)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The With method lets you specify an expression that identifies a property, as well
as the value that should be assigned to that property. When you do that, AutoFixture
will never attempt to assign an anonymous value to that property, but will instead
use the value you specified.
&lt;/p&gt;
&lt;p&gt;
In most cases, just creating a truly anonymous instance and subsequently explicitly
assigning any significant values is easier, but using the Build method with one or
more calls to the With method gives you the power to override any property assignments
before the instance is created.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a5013fc1-44d8-4930-aa7d-77aee8d60db6" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,a5013fc1-44d8-4930-aa7d-77aee8d60db6.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is really nothing new, but I don't think I've explicitly stated this before:
It makes a lot of sense to view delegates as anonymous one-method interfaces.
</p>
        <p>
Many people liken delegates to function pointers. While that's probably correct (I
wouldn't really know), it's not a very object-oriented view to take – at least not
when we are dealing with managed code. To me, it makes more sense to view delegates
as anonymous one-method interfaces.
</p>
        <p>
Lets consider a simple example. As always, we have the ubiquitous MyClass with its
DoStuff method. In this example, DoStuff takes as input an abstraction that takes
a string as input and returns an integer – let's imagine that this is some kind of
Strategy (notice the capital <em>S</em> – I'm talking about the design pattern, here).
</p>
        <p>
In traditional object-oriented design, we could solve this by introducing the IMyInterface
type:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IMyInterface\par ??\cf0 \{\par ??    \cf1 int\cf0  DoIt(\cf1 string\cf0  message);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IMyInterface</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> DoIt(<span style="color: blue">string</span> message);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The implementation of DoStuff is simply:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 IMyInterface\cf0  strategy)\par ??\{\par ??    \cf1 return\cf0  strategy.DoIt(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">string</span> DoStuff(<span style="color: #2b91af">IMyInterface</span> strategy)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> strategy.DoIt(<span style="color: #a31515">"Ploeh"</span>).ToString();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Hardly rocket science…
</p>
        <p>
However, defining a completely new interface just to do this is not really necessary,
since we could just as well have implemented DoStuff with a Func&lt;string, int&gt;:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 Func\cf0 &lt;\cf1 string\cf0 , \cf1 int\cf0 &gt; strategy)\par ??\{\par ??    \cf1 return\cf0  strategy(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">string</span> DoStuff(<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;
strategy)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> strategy(<span style="color: #a31515">"Ploeh"</span>).ToString();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This not only frees us from defining a new interface, but also from implementing that
interface to use the DoStuff method. Instead, we can simply pass a lambda expression:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 string\cf0  result = sut.DoStuff(s =&gt; s.Count());}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">string</span> result
= sut.DoStuff(s =&gt; s.Count());</pre>
        </div>
        <p>
What's most amazing is that <a href="http://ayende.com/projects/rhino-mocks.aspx">RhinoMocks</a> understands
and treats delegates just like other abstract types, so that we can write the following
to treat it as a mock:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue0;\red0\green0\blue255;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 Func\cf0 &lt;\cf5 string\cf0 , \cf5 int\cf0 &gt; mock =\par ??    \cf3 MockRepository\cf0 .GenerateMock&lt;\cf3 Func\cf0 &lt;\cf5 string\cf0 , \cf5 int\cf0 &gt;&gt;();\par ??mock.Expect(f =&gt; f(\cf6 "Ploeh"\cf0 )).Return(42);\par ??\cf5 var\cf0  sut = \cf5 new\cf0  \cf3 MyClass\cf0 ();\par ??\cf1 // Exercise system\par ??\cf5 string\cf0  result = sut.DoStuff(mock);\par ??\cf1 // Verify outcome\par ??\cf0 mock.VerifyAllExpectations();\par ??\cf1 // Teardown}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: green">//
Fixture setup</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;
mock =</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;&gt;();</pre>
          <pre style="margin: 0px">mock.Expect(f =&gt; f(<span style="color: #a31515">"Ploeh"</span>)).Return(42);</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Exercise system</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">string</span> result
= sut.DoStuff(mock);</pre>
          <pre style="margin: 0px">
            <span style="color: green">// Verify
outcome</span>
          </pre>
          <pre style="margin: 0px">mock.VerifyAllExpectations();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Teardown</span>
          </pre>
        </div>
        <p>
Whenever possible, I prefer to model my APIs with delegates instead of one-method
interfaces, since it gives me greater flexibility and less infrastructure code.
</p>
        <p>
Obviously, this technique only works as long as you only need to abstract a single
method. As soon as your abstraction needs a second method, you will need to introduce
a proper interface or, preferably, an abstract base class.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b" />
      </body>
      <title>Delegates Are Anonymous Interfaces</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx</link>
      <pubDate>Thu, 28 May 2009 20:19:04 GMT</pubDate>
      <description>&lt;p&gt;
This is really nothing new, but I don't think I've explicitly stated this before:
It makes a lot of sense to view delegates as anonymous one-method interfaces.
&lt;/p&gt;
&lt;p&gt;
Many people liken delegates to function pointers. While that's probably correct (I
wouldn't really know), it's not a very object-oriented view to take – at least not
when we are dealing with managed code. To me, it makes more sense to view delegates
as anonymous one-method interfaces.
&lt;/p&gt;
&lt;p&gt;
Lets consider a simple example. As always, we have the ubiquitous MyClass with its
DoStuff method. In this example, DoStuff takes as input an abstraction that takes
a string as input and returns an integer – let's imagine that this is some kind of
Strategy (notice the capital &lt;em&gt;S&lt;/em&gt; – I'm talking about the design pattern, here).
&lt;/p&gt;
&lt;p&gt;
In traditional object-oriented design, we could solve this by introducing the IMyInterface
type:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IMyInterface\par ??\cf0 \{\par ??    \cf1 int\cf0  DoIt(\cf1 string\cf0  message);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;interface&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; DoIt(&lt;span style="color: blue"&gt;string&lt;/span&gt; message);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The implementation of DoStuff is simply:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 IMyInterface\cf0  strategy)\par ??\{\par ??    \cf1 return\cf0  strategy.DoIt(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; DoStuff(&lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt; strategy)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; strategy.DoIt(&lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;).ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Hardly rocket science…
&lt;/p&gt;
&lt;p&gt;
However, defining a completely new interface just to do this is not really necessary,
since we could just as well have implemented DoStuff with a Func&amp;lt;string, int&amp;gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 Func\cf0 &amp;lt;\cf1 string\cf0 , \cf1 int\cf0 &amp;gt; strategy)\par ??\{\par ??    \cf1 return\cf0  strategy(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; DoStuff(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;
strategy)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; strategy(&lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;).ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This not only frees us from defining a new interface, but also from implementing that
interface to use the DoStuff method. Instead, we can simply pass a lambda expression:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 string\cf0  result = sut.DoStuff(s =&amp;gt; s.Count());}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;string&lt;/span&gt; result
= sut.DoStuff(s =&amp;gt; s.Count());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What's most amazing is that &lt;a href="http://ayende.com/projects/rhino-mocks.aspx"&gt;RhinoMocks&lt;/a&gt; understands
and treats delegates just like other abstract types, so that we can write the following
to treat it as a mock:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue0;\red0\green0\blue255;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 Func\cf0 &amp;lt;\cf5 string\cf0 , \cf5 int\cf0 &amp;gt; mock =\par ??    \cf3 MockRepository\cf0 .GenerateMock&amp;lt;\cf3 Func\cf0 &amp;lt;\cf5 string\cf0 , \cf5 int\cf0 &amp;gt;&amp;gt;();\par ??mock.Expect(f =&amp;gt; f(\cf6 "Ploeh"\cf0 )).Return(42);\par ??\cf5 var\cf0  sut = \cf5 new\cf0  \cf3 MyClass\cf0 ();\par ??\cf1 // Exercise system\par ??\cf5 string\cf0  result = sut.DoStuff(mock);\par ??\cf1 // Verify outcome\par ??\cf0 mock.VerifyAllExpectations();\par ??\cf1 // Teardown}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;
mock =&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mock.Expect(f =&amp;gt; f(&lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;)).Return(42);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;string&lt;/span&gt; result
= sut.DoStuff(mock);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;// Verify
outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mock.VerifyAllExpectations();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Whenever possible, I prefer to model my APIs with delegates instead of one-method
interfaces, since it gives me greater flexibility and less infrastructure code.
&lt;/p&gt;
&lt;p&gt;
Obviously, this technique only works as long as you only need to abstract a single
method. As soon as your abstraction needs a second method, you will need to introduce
a proper interface or, preferably, an abstract base class.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</comments>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Until now, I've shown you how you can make wholesale adjustments or customizations
to an entire Fixture instance, effectively changing the way it creates all instances
of a particular type.
</p>
        <p>
In some scenarios, you'd rather want to customize how a single instance is created
without influencing other instances of the same type. For this purpose, <a href="http://autofixture.codeplex.com/">AutoFixture</a> includes
a class called ObjectBuilder&lt;T&gt; that can be used to do exactly that. 
</p>
        <p>
The easiest way to get an instance of this class is by calling Build on a Fixture
instance. This will give you an instance of ObjectBuilder&lt;T&gt; that you can use
to customize the build steps. When you are done, CreateAnonymous returns the built
instance.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.Build&lt;\cf4 MyClass\cf0 &gt;().CreateAnonymous();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.Build&lt;<span style="color: #2b91af">MyClass</span>&gt;().CreateAnonymous();</pre>
        </div>
        <p>
This particular example doesn't define any customizations, so it's equivalent to
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&lt;\cf4 MyClass\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mc
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
        </div>
        <p>
In fact, Fixture.CreateAnonymous is little more than a convenience method wrapping
an ObjectBuilder (there's a few extra differences, but that's a topic for another
post).
</p>
        <p>
It's worth noting that the object specified by the type parameter to the Build method
is first created when you call CreateAnonymous.
</p>
        <p>
In future posts I'll demonstrate how to use the Build method to customize individual <a href="http://blogs.msdn.com/ploeh/archive/2008/11/17/anonymous-variables.aspx">anonymous
variables</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e" />
      </body>
      <title>The AutoFixture Builder</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/26/TheAutoFixtureBuilder.aspx</link>
      <pubDate>Tue, 26 May 2009 21:30:35 GMT</pubDate>
      <description>&lt;p&gt;
Until now, I've shown you how you can make wholesale adjustments or customizations
to an entire Fixture instance, effectively changing the way it creates all instances
of a particular type.
&lt;/p&gt;
&lt;p&gt;
In some scenarios, you'd rather want to customize how a single instance is created
without influencing other instances of the same type. For this purpose, &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; includes
a class called ObjectBuilder&amp;lt;T&amp;gt; that can be used to do exactly that. 
&lt;/p&gt;
&lt;p&gt;
The easiest way to get an instance of this class is by calling Build on a Fixture
instance. This will give you an instance of ObjectBuilder&amp;lt;T&amp;gt; that you can use
to customize the build steps. When you are done, CreateAnonymous returns the built
instance.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.Build&amp;lt;\cf4 MyClass\cf0 &amp;gt;().CreateAnonymous();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.Build&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;().CreateAnonymous();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This particular example doesn't define any customizations, so it's equivalent to
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  mc = fixture.CreateAnonymous&amp;lt;\cf4 MyClass\cf0 &amp;gt;();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mc
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In fact, Fixture.CreateAnonymous is little more than a convenience method wrapping
an ObjectBuilder (there's a few extra differences, but that's a topic for another
post).
&lt;/p&gt;
&lt;p&gt;
It's worth noting that the object specified by the type parameter to the Build method
is first created when you call CreateAnonymous.
&lt;/p&gt;
&lt;p&gt;
In future posts I'll demonstrate how to use the Build method to customize individual &lt;a href="http://blogs.msdn.com/ploeh/archive/2008/11/17/anonymous-variables.aspx"&gt;anonymous
variables&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,7c7377c0-0ffa-4e8f-a0e4-11b2d4cc549e.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=56eac1c1-e5f8-4a59-9e09-24bb1541c34a</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,56eac1c1-e5f8-4a59-9e09-24bb1541c34a.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,56eac1c1-e5f8-4a59-9e09-24bb1541c34a.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=56eac1c1-e5f8-4a59-9e09-24bb1541c34a</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This post describes a particular problem I ran into when working with the Microsoft
Sync Framework. Since I found a solution, I’m sharing it here to help others. If you
are not having this particular problem, it’s quite safe to skip reading the rest of
the post :)
</p>
        <p>
While developing a SyncProvider, I wanted to create and execute a series of <a href="http://blogs.msdn.com/ploeh/archive/2006/08/27/727211.aspx">Integration
Tests</a> to drive my development effort. In order to do that, I wrote a simple test
that simply created a SyncOrchestrator instance and invoked its Synchronize method.
</p>
        <p>
Running this test gave me this error message:
</p>
        <p>
“Microsoft.Synchronization.SyncException: Retrieving the COM class factory for component
with CLSID {A7B3B4EE-925C-4D6C-B007-A4A6A0B09143} failed due to the following error:
80040154. ---&gt;  System.Runtime.InteropServices.COMException: Retrieving the
COM class factory for component with CLSID {A7B3B4EE-925C-4D6C-B007-A4A6A0B09143}
failed due to the following error: 80040154.”
</p>
        <p>
It’s not often I see a COMException these days, so I was initially baffled. Since
the Sync Framework also has an unmanaged API, this is really not surprising, but that
didn’t help me solve my problem.
</p>
        <p>
What was even weirder was that when I tried running the same code in my application,
this exception was <em>not</em> being thrown.
</p>
        <p>
It took me a couple of hours to figure out what the problem was.
</p>
        <p>
Here’s a little hint: I’m running Windows Vista x64.
</p>
        <p>
No: The issue is not that I’m running Vista :)
</p>
        <p>
Even on x64, Visual Studio runs as a 32-bit process, and so does MSTest. Since my
code was compiled to <em>Any CPU</em>, the application itself was running in a 64-bit
process, whereas my unit test was running in a 32-bit process.
</p>
        <p>
I tried changing my build output to x86, and now the application started throwing
the same exception as the unit test did.
</p>
        <p>
In other words: When running in a 64-bit process, everything worked as intended. When
running in a 32-bit process, a COMException was thrown.
</p>
        <p>
As it turned out, I had only installed the 64-bit version of the Sync Framework, and
even though the SDK seems to contain builds for the other architectures as well, the
COM Server wasn’t properly registered for 32-bit use.
</p>
        <p>
To resolve this issue, I downloaded and installed the x86 version of the Sync Framework
as well, and the problem went away.
</p>
        <p>
If you are having the same problem, I hope this post helps you resolve it.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=56eac1c1-e5f8-4a59-9e09-24bb1541c34a" />
      </body>
      <title>SyncOrchestrator.Synchronize() Throws COMException When Unit Testing</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,56eac1c1-e5f8-4a59-9e09-24bb1541c34a.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/21/SyncOrchestratorSynchronizeThrowsCOMExceptionWhenUnitTesting.aspx</link>
      <pubDate>Thu, 21 May 2009 18:54:01 GMT</pubDate>
      <description>&lt;p&gt;
This post describes a particular problem I ran into when working with the Microsoft
Sync Framework. Since I found a solution, I’m sharing it here to help others. If you
are not having this particular problem, it’s quite safe to skip reading the rest of
the post :)
&lt;/p&gt;
&lt;p&gt;
While developing a SyncProvider, I wanted to create and execute a series of &lt;a href="http://blogs.msdn.com/ploeh/archive/2006/08/27/727211.aspx"&gt;Integration
Tests&lt;/a&gt; to drive my development effort. In order to do that, I wrote a simple test
that simply created a SyncOrchestrator instance and invoked its Synchronize method.
&lt;/p&gt;
&lt;p&gt;
Running this test gave me this error message:
&lt;/p&gt;
&lt;p&gt;
“Microsoft.Synchronization.SyncException: Retrieving the COM class factory for component
with CLSID {A7B3B4EE-925C-4D6C-B007-A4A6A0B09143} failed due to the following error:
80040154. ---&amp;gt;&amp;nbsp; System.Runtime.InteropServices.COMException: Retrieving the
COM class factory for component with CLSID {A7B3B4EE-925C-4D6C-B007-A4A6A0B09143}
failed due to the following error: 80040154.”
&lt;/p&gt;
&lt;p&gt;
It’s not often I see a COMException these days, so I was initially baffled. Since
the Sync Framework also has an unmanaged API, this is really not surprising, but that
didn’t help me solve my problem.
&lt;/p&gt;
&lt;p&gt;
What was even weirder was that when I tried running the same code in my application,
this exception was &lt;em&gt;not&lt;/em&gt; being thrown.
&lt;/p&gt;
&lt;p&gt;
It took me a couple of hours to figure out what the problem was.
&lt;/p&gt;
&lt;p&gt;
Here’s a little hint: I’m running Windows Vista x64.
&lt;/p&gt;
&lt;p&gt;
No: The issue is not that I’m running Vista :)
&lt;/p&gt;
&lt;p&gt;
Even on x64, Visual Studio runs as a 32-bit process, and so does MSTest. Since my
code was compiled to &lt;em&gt;Any CPU&lt;/em&gt;, the application itself was running in a 64-bit
process, whereas my unit test was running in a 32-bit process.
&lt;/p&gt;
&lt;p&gt;
I tried changing my build output to x86, and now the application started throwing
the same exception as the unit test did.
&lt;/p&gt;
&lt;p&gt;
In other words: When running in a 64-bit process, everything worked as intended. When
running in a 32-bit process, a COMException was thrown.
&lt;/p&gt;
&lt;p&gt;
As it turned out, I had only installed the 64-bit version of the Sync Framework, and
even though the SDK seems to contain builds for the other architectures as well, the
COM Server wasn’t properly registered for 32-bit use.
&lt;/p&gt;
&lt;p&gt;
To resolve this issue, I downloaded and installed the x86 version of the Sync Framework
as well, and the problem went away.
&lt;/p&gt;
&lt;p&gt;
If you are having the same problem, I hope this post helps you resolve it.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=56eac1c1-e5f8-4a59-9e09-24bb1541c34a" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,56eac1c1-e5f8-4a59-9e09-24bb1541c34a.aspx</comments>
      <category>Sync</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=1d8cf097-ca10-45d7-aac5-7cf0033f2756</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,1d8cf097-ca10-45d7-aac5-7cf0033f2756.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,1d8cf097-ca10-45d7-aac5-7cf0033f2756.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=1d8cf097-ca10-45d7-aac5-7cf0033f2756</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Today I've created a new release (.8.1 for lack of a better version number) of <a href="http://autofixture.codeplex.com/">AutoFixture</a>.
While it contains some breaking changes, they all relate to features that I have yet
to cover here on the blog – in other words: All the examples that I've posted so far
are still valid.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1d8cf097-ca10-45d7-aac5-7cf0033f2756" />
      </body>
      <title>AutoFixture .8.1 Released</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,1d8cf097-ca10-45d7-aac5-7cf0033f2756.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/17/AutoFixture81Released.aspx</link>
      <pubDate>Sun, 17 May 2009 07:48:36 GMT</pubDate>
      <description>&lt;p&gt;
Today I've created a new release (.8.1 for lack of a better version number) of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;.
While it contains some breaking changes, they all relate to features that I have yet
to cover here on the blog – in other words: All the examples that I've posted so far
are still valid.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1d8cf097-ca10-45d7-aac5-7cf0033f2756" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,1d8cf097-ca10-45d7-aac5-7cf0033f2756.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=ef5bab91-8b41-4cc5-9e44-f6accd855d64</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,ef5bab91-8b41-4cc5-9e44-f6accd855d64.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,ef5bab91-8b41-4cc5-9e44-f6accd855d64.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ef5bab91-8b41-4cc5-9e44-f6accd855d64</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Dear reader, I hope you are still with me!
</p>
        <p>
After eight posts of <a href="http://autofixture.codeplex.com/">AutoFixture</a> feature
walkthroughs, I can't blame you for wondering why this tool might even be relevant
to you. In this post, we'll finally begin to look at how AutoFixture can help you
towards <a href="http://blog.ploeh.dk/2009/01/28/ZeroFrictionTDD.aspx">Zero-Friction
TDD</a>!
</p>
        <p>
In an earlier post, I described how the <a href="http://blog.ploeh.dk/2009/03/16/FixtureObject.aspx">Fixture
Object</a> pattern can help you greatly reduce the amount of test code that you have
to write. Since AutoFixture was designed to act as a general-purpose Fixture Object,
it can help you reduce the amount of test code even further, letting you focus on <a href="http://blog.ploeh.dk/2009/03/10/SpecificationDrivenDevelopment.aspx">specifying
the behavior</a> of your <a href="http://xunitpatterns.com/SUT.html">SUT</a>.
</p>
        <p>
In that former post, the original example was this complex test that I will repeat
in it's entirety for your benefit (or horror):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  NumberSumIsCorrect_Na\u239 ?ve()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf3 Thing\cf0  thing1 = \cf4 new\cf0  \cf3 Thing\cf0 ()\par ??    \{\par ??        Number = 3,\par ??        Text = \cf6 "Anonymous text 1"\par ??\cf0     \};\par ??    \cf3 Thing\cf0  thing2 = \cf4 new\cf0  \cf3 Thing\cf0 ()\par ??    \{\par ??        Number = 6,\par ??        Text = \cf6 "Anonymous text 2"\par ??\cf0     \};\par ??    \cf3 Thing\cf0  thing3 = \cf4 new\cf0  \cf3 Thing\cf0 ()\par ??    \{\par ??        Number = 1,\par ??        Text = \cf6 "Anonymous text 3"\par ??\cf0     \};\par ??\par ??    \cf4 int\cf0  expectedSum = \cf4 new\cf0 [] \{ thing1, thing2, thing3 \}.\par ??        Select(t =&gt; t.Number).Sum();\par ??\par ??    \cf3 IMyInterface\cf0  fake = \cf4 new\cf0  \cf3 FakeMyInterface\cf0 ();\par ??    fake.AddThing(thing1);\par ??    fake.AddThing(thing2);\par ??    fake.AddThing(thing3);\par ??\par ??    \cf3 MyClass\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 (fake);\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 int\cf0  result = sut.CalculateSumOfThings();\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&lt;\cf4 int\cf0 &gt;(expectedSum, result,\par ??        \cf6 "Sum of things"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> NumberSumIsCorrect_Naïve()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Thing</span> thing1
= <span style="color: blue">new</span><span style="color: #2b91af">Thing</span>()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        Number = 3,</pre>
          <pre style="margin: 0px">        Text = <span style="color: #a31515">"Anonymous
text 1"</span></pre>
          <pre style="margin: 0px">    };</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Thing</span> thing2
= <span style="color: blue">new</span><span style="color: #2b91af">Thing</span>()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        Number = 6,</pre>
          <pre style="margin: 0px">        Text = <span style="color: #a31515">"Anonymous
text 2"</span></pre>
          <pre style="margin: 0px">    };</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Thing</span> thing3
= <span style="color: blue">new</span><span style="color: #2b91af">Thing</span>()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        Number = 1,</pre>
          <pre style="margin: 0px">        Text = <span style="color: #a31515">"Anonymous
text 3"</span></pre>
          <pre style="margin: 0px">    };</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> expectedSum
= <span style="color: blue">new</span>[] { thing1, thing2, thing3 }.</pre>
          <pre style="margin: 0px">        Select(t =&gt; t.Number).Sum();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IMyInterface</span> fake
= <span style="color: blue">new</span><span style="color: #2b91af">FakeMyInterface</span>();</pre>
          <pre style="margin: 0px">    fake.AddThing(thing1);</pre>
          <pre style="margin: 0px">    fake.AddThing(thing2);</pre>
          <pre style="margin: 0px">    fake.AddThing(thing3);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MyClass</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>(fake);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> result
= sut.CalculateSumOfThings();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual&lt;<span style="color: blue">int</span>&gt;(expectedSum,
result,</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"Sum
of things"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This test consists of 18 lines of code.
</p>
        <p>
Using the Fixture Object pattern, I was able to cut that down to 7 lines of code,
which is a 61% improvement (however, the downside was an additional 19 lines of (reusable)
code for MyClassFixture, so the benefit can only be reaped when you have multiple
tests leveraged by the same Fixture Object. This was all covered in the <a href="http://blog.ploeh.dk/2009/03/16/FixtureObject.aspx">former
post, to which I will refer you</a>).
</p>
        <p>
With AutoFixture, we can do much better. Here's a one-off rewrite of the unit test
using AutoFixture:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  NumberSumIsCorrect_AutoFixture()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf3 Fixture\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf3 IMyInterface\cf0  fake = \cf4 new\cf0  \cf3 FakeMyInterface\cf0 ();\par ??    fixture.Register&lt;\cf3 IMyInterface\cf0 &gt;(() =&gt; fake);\par ??\par ??    \cf4 var\cf0  things = fixture.CreateMany&lt;\cf3 Thing\cf0 &gt;().ToList();\par ??    things.ForEach(t =&gt; fake.AddThing(t));\par ??    \cf4 int\cf0  expectedSum = things.Select(t =&gt; t.Number).Sum();\par ??\par ??    \cf3 MyClass\cf0  sut = fixture.CreateAnonymous&lt;\cf3 MyClass\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 int\cf0  result = sut.CalculateSumOfThings();\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&lt;\cf4 int\cf0 &gt;(expectedSum, result,\par ??        \cf6 "Sum of things"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> NumberSumIsCorrect_AutoFixture()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Fixture</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>();</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IMyInterface</span> fake
= <span style="color: blue">new</span><span style="color: #2b91af">FakeMyInterface</span>();</pre>
          <pre style="margin: 0px">    fixture.Register&lt;<span style="color: #2b91af">IMyInterface</span>&gt;(()
=&gt; fake);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> things
= fixture.CreateMany&lt;<span style="color: #2b91af">Thing</span>&gt;().ToList();</pre>
          <pre style="margin: 0px">    things.ForEach(t =&gt; fake.AddThing(t));</pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> expectedSum
= things.Select(t =&gt; t.Number).Sum();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MyClass</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> result
= sut.CalculateSumOfThings();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual&lt;<span style="color: blue">int</span>&gt;(expectedSum,
result,</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"Sum
of things"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this test, I <a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx">map
the concrete fake instance to the IMyInterface type</a> in the fixture object, and
then use its ability to <a href="http://blog.ploeh.dk/2009/05/11/AnonymousSequencesWithAutoFixture.aspx">create
many anonymous instances with one method call</a>. Before exercising the SUT, I also
use the fixture instance as a <a href="http://blog.ploeh.dk/2009/02/13/SUTFactory.aspx">SUT
Factory</a>.
</p>
        <p>
Apart from AutoFixture (and FakeMyInterface, which is invariant for all variations,
and thus kept out of the comparison), this test stands alone, but still manages to
reduce the number of code lines to 10 lines – a 44% improvement! In my book, that's
already a significant gain in productivity and maintainability, but we can do better!
</p>
        <p>
If we need to test MyClass repeatedly in similar ways, we can move the common code
to a Fixture Object based on AutoFixture, and the test can be refactored to this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  NumberSumIsCorrect_DerivedFixture()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf3 MyClassFixture\cf0  fixture = \cf4 new\cf0  \cf3 MyClassFixture\cf0 ();\par ??    fixture.AddManyTo(fixture.Things);\par ??\par ??    \cf4 int\cf0  expectedSum = \par ??        fixture.Things.Select(t =&gt; t.Number).Sum();\par ??    \cf3 MyClass\cf0  sut = fixture.CreateAnonymous&lt;\cf3 MyClass\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 int\cf0  result = sut.CalculateSumOfThings();\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&lt;\cf4 int\cf0 &gt;(expectedSum, result,\par ??        \cf6 "Sum of things"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">TestMethod</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> NumberSumIsCorrect_DerivedFixture()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Fixture setup</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MyClassFixture</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">MyClassFixture</span>();</pre>
          <pre style="margin: 0px">    fixture.AddManyTo(fixture.Things);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> expectedSum
= </pre>
          <pre style="margin: 0px">        fixture.Things.Select(t =&gt; t.Number).Sum();</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MyClass</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">MyClass</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> result
= sut.CalculateSumOfThings();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual&lt;<span style="color: blue">int</span>&gt;(expectedSum,
result,</pre>
          <pre style="margin: 0px">        <span style="color: #a31515">"Sum
of things"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Now we are back at 7 lines of code, which is on par with the original Fixture Object-based
test, but now MyClassFixture is reduced to 8 lines of code:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 class\cf0  \cf4 MyClassFixture\cf0  : \cf4 Fixture\par ??\cf0 \{\par ??    \cf1 internal\cf0  MyClassFixture()\par ??    \{\par ??        \cf1 this\cf0 .Things = \cf1 new\cf0  \cf4 List\cf0 &lt;\cf4 Thing\cf0 &gt;();\par ??        \cf1 this\cf0 .Register&lt;\cf4 IMyInterface\cf0 &gt;(() =&gt;\par ??            \{\par ??                \cf1 var\cf0  fake = \cf1 new\cf0  \cf4 FakeMyInterface\cf0 ();\par ??                \cf1 this\cf0 .Things.ToList().ForEach(t =&gt;\par ??                    fake.AddThing(t));\par ??                \cf1 return\cf0  fake;\par ??            \});\par ??    \}\par ??\par ??    \cf1 internal\cf0  \cf4 IList\cf0 &lt;\cf4 Thing\cf0 &gt; Things \{ \cf1 get\cf0 ; \cf1 private\cf0  \cf1 set\cf0 ; \}\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">internal</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">MyClassFixture</span> : <span style="color: #2b91af">Fixture</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">internal</span> MyClassFixture()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.Things
= <span style="color: blue">new</span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Thing</span>&gt;();</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.Register&lt;<span style="color: #2b91af">IMyInterface</span>&gt;(()
=&gt;</pre>
          <pre style="margin: 0px">            {</pre>
          <pre style="margin: 0px">                <span style="color: blue">var</span> fake
= <span style="color: blue">new</span><span style="color: #2b91af">FakeMyInterface</span>();</pre>
          <pre style="margin: 0px">                <span style="color: blue">this</span>.Things.ToList().ForEach(t
=&gt;</pre>
          <pre style="margin: 0px">                    fake.AddThing(t));</pre>
          <pre style="margin: 0px">                <span style="color: blue">return</span> fake;</pre>
          <pre style="margin: 0px">            });</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">internal</span><span style="color: #2b91af">IList</span>&lt;<span style="color: #2b91af">Thing</span>&gt;
Things { <span style="color: blue">get</span>; <span style="color: blue">private</span><span style="color: blue">set</span>;
}</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice how I've moved the IMyInterface-to-FakeMyInterface mapping to MyClassFixture.
Whenever it's asked to create a new instance of IMyInterface, MyClassFixture makes
sure to add all the Thing instances to the fake before returning it.
</p>
        <p>
Compared to the former Fixture Object of 19 lines, that's another 58% improvement.
Considering some of the APIs I encounter in my daily work, the above example is even
rather simple. The more complex and demanding your SUT's API is, the greater the gain
from using AutoFixture will be, since it's going to figure out much of the routine
stuff for you.
</p>
        <p>
With this post, I hope I have given you a taste of the power that AutoFixture provides.
It allows you to focus on specifying the behavior of your SUT, while taking care of
all the infrastructure tedium that tends to get in the way.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ef5bab91-8b41-4cc5-9e44-f6accd855d64" />
      </body>
      <title>AutoFixture As Fixture Object</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,ef5bab91-8b41-4cc5-9e44-f6accd855d64.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/15/AutoFixtureAsFixtureObject.aspx</link>
      <pubDate>Fri, 15 May 2009 05:34:00 GMT</pubDate>
      <description>&lt;p&gt;
Dear reader, I hope you are still with me!
&lt;/p&gt;
&lt;p&gt;
After eight posts of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; feature
walkthroughs, I can't blame you for wondering why this tool might even be relevant
to you. In this post, we'll finally begin to look at how AutoFixture can help you
towards &lt;a href="http://blog.ploeh.dk/2009/01/28/ZeroFrictionTDD.aspx"&gt;Zero-Friction
TDD&lt;/a&gt;!
&lt;/p&gt;
&lt;p&gt;
In an earlier post, I described how the &lt;a href="http://blog.ploeh.dk/2009/03/16/FixtureObject.aspx"&gt;Fixture
Object&lt;/a&gt; pattern can help you greatly reduce the amount of test code that you have
to write. Since AutoFixture was designed to act as a general-purpose Fixture Object,
it can help you reduce the amount of test code even further, letting you focus on &lt;a href="http://blog.ploeh.dk/2009/03/10/SpecificationDrivenDevelopment.aspx"&gt;specifying
the behavior&lt;/a&gt; of your &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
In that former post, the original example was this complex test that I will repeat
in it's entirety for your benefit (or horror):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  NumberSumIsCorrect_Na\u239 ?ve()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf3 Thing\cf0  thing1 = \cf4 new\cf0  \cf3 Thing\cf0 ()\par ??    \{\par ??        Number = 3,\par ??        Text = \cf6 "Anonymous text 1"\par ??\cf0     \};\par ??    \cf3 Thing\cf0  thing2 = \cf4 new\cf0  \cf3 Thing\cf0 ()\par ??    \{\par ??        Number = 6,\par ??        Text = \cf6 "Anonymous text 2"\par ??\cf0     \};\par ??    \cf3 Thing\cf0  thing3 = \cf4 new\cf0  \cf3 Thing\cf0 ()\par ??    \{\par ??        Number = 1,\par ??        Text = \cf6 "Anonymous text 3"\par ??\cf0     \};\par ??\par ??    \cf4 int\cf0  expectedSum = \cf4 new\cf0 [] \{ thing1, thing2, thing3 \}.\par ??        Select(t =&amp;gt; t.Number).Sum();\par ??\par ??    \cf3 IMyInterface\cf0  fake = \cf4 new\cf0  \cf3 FakeMyInterface\cf0 ();\par ??    fake.AddThing(thing1);\par ??    fake.AddThing(thing2);\par ??    fake.AddThing(thing3);\par ??\par ??    \cf3 MyClass\cf0  sut = \cf4 new\cf0  \cf3 MyClass\cf0 (fake);\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 int\cf0  result = sut.CalculateSumOfThings();\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&amp;lt;\cf4 int\cf0 &amp;gt;(expectedSum, result,\par ??        \cf6 "Sum of things"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; NumberSumIsCorrect_Naïve()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt; thing1
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Number = 3,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Text = &lt;span style="color: #a31515"&gt;"Anonymous
text 1"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt; thing2
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Number = 6,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Text = &lt;span style="color: #a31515"&gt;"Anonymous
text 2"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt; thing3
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Number = 1,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Text = &lt;span style="color: #a31515"&gt;"Anonymous
text 3"&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; };&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; expectedSum
= &lt;span style="color: blue"&gt;new&lt;/span&gt;[] { thing1, thing2, thing3 }.&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Select(t =&amp;gt; t.Number).Sum();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt; fake
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FakeMyInterface&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fake.AddThing(thing1);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fake.AddThing(thing2);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fake.AddThing(thing3);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;(fake);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; result
= sut.CalculateSumOfThings();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(expectedSum,
result,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"Sum
of things"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This test consists of 18 lines of code.
&lt;/p&gt;
&lt;p&gt;
Using the Fixture Object pattern, I was able to cut that down to 7 lines of code,
which is a 61% improvement (however, the downside was an additional 19 lines of (reusable)
code for MyClassFixture, so the benefit can only be reaped when you have multiple
tests leveraged by the same Fixture Object. This was all covered in the &lt;a href="http://blog.ploeh.dk/2009/03/16/FixtureObject.aspx"&gt;former
post, to which I will refer you&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
With AutoFixture, we can do much better. Here's a one-off rewrite of the unit test
using AutoFixture:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  NumberSumIsCorrect_AutoFixture()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf3 Fixture\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf3 IMyInterface\cf0  fake = \cf4 new\cf0  \cf3 FakeMyInterface\cf0 ();\par ??    fixture.Register&amp;lt;\cf3 IMyInterface\cf0 &amp;gt;(() =&amp;gt; fake);\par ??\par ??    \cf4 var\cf0  things = fixture.CreateMany&amp;lt;\cf3 Thing\cf0 &amp;gt;().ToList();\par ??    things.ForEach(t =&amp;gt; fake.AddThing(t));\par ??    \cf4 int\cf0  expectedSum = things.Select(t =&amp;gt; t.Number).Sum();\par ??\par ??    \cf3 MyClass\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 MyClass\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 int\cf0  result = sut.CalculateSumOfThings();\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&amp;lt;\cf4 int\cf0 &amp;gt;(expectedSum, result,\par ??        \cf6 "Sum of things"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; NumberSumIsCorrect_AutoFixture()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt; fake
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FakeMyInterface&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Register&amp;lt;&lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt;&amp;gt;(()
=&amp;gt; fake);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; things
= fixture.CreateMany&amp;lt;&lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt;&amp;gt;().ToList();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; things.ForEach(t =&amp;gt; fake.AddThing(t));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; expectedSum
= things.Select(t =&amp;gt; t.Number).Sum();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; result
= sut.CalculateSumOfThings();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(expectedSum,
result,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"Sum
of things"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this test, I &lt;a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx"&gt;map
the concrete fake instance to the IMyInterface type&lt;/a&gt; in the fixture object, and
then use its ability to &lt;a href="http://blog.ploeh.dk/2009/05/11/AnonymousSequencesWithAutoFixture.aspx"&gt;create
many anonymous instances with one method call&lt;/a&gt;. Before exercising the SUT, I also
use the fixture instance as a &lt;a href="http://blog.ploeh.dk/2009/02/13/SUTFactory.aspx"&gt;SUT
Factory&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Apart from AutoFixture (and FakeMyInterface, which is invariant for all variations,
and thus kept out of the comparison), this test stands alone, but still manages to
reduce the number of code lines to 10 lines – a 44% improvement! In my book, that's
already a significant gain in productivity and maintainability, but we can do better!
&lt;/p&gt;
&lt;p&gt;
If we need to test MyClass repeatedly in similar ways, we can move the common code
to a Fixture Object based on AutoFixture, and the test can be refactored to this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;\red163\green21\blue21;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  NumberSumIsCorrect_DerivedFixture()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf3 MyClassFixture\cf0  fixture = \cf4 new\cf0  \cf3 MyClassFixture\cf0 ();\par ??    fixture.AddManyTo(fixture.Things);\par ??\par ??    \cf4 int\cf0  expectedSum = \par ??        fixture.Things.Select(t =&amp;gt; t.Number).Sum();\par ??    \cf3 MyClass\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 MyClass\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 int\cf0  result = sut.CalculateSumOfThings();\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual&amp;lt;\cf4 int\cf0 &amp;gt;(expectedSum, result,\par ??        \cf6 "Sum of things"\cf0 );\par ??    \cf5 // Teardown\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;TestMethod&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; NumberSumIsCorrect_DerivedFixture()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MyClassFixture&lt;/span&gt; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClassFixture&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.AddManyTo(fixture.Things);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; expectedSum
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Things.Select(t =&amp;gt; t.Number).Sum();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; result
= sut.CalculateSumOfThings();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.AreEqual&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(expectedSum,
result,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"Sum
of things"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Now we are back at 7 lines of code, which is on par with the original Fixture Object-based
test, but now MyClassFixture is reduced to 8 lines of code:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 class\cf0  \cf4 MyClassFixture\cf0  : \cf4 Fixture\par ??\cf0 \{\par ??    \cf1 internal\cf0  MyClassFixture()\par ??    \{\par ??        \cf1 this\cf0 .Things = \cf1 new\cf0  \cf4 List\cf0 &amp;lt;\cf4 Thing\cf0 &amp;gt;();\par ??        \cf1 this\cf0 .Register&amp;lt;\cf4 IMyInterface\cf0 &amp;gt;(() =&amp;gt;\par ??            \{\par ??                \cf1 var\cf0  fake = \cf1 new\cf0  \cf4 FakeMyInterface\cf0 ();\par ??                \cf1 this\cf0 .Things.ToList().ForEach(t =&amp;gt;\par ??                    fake.AddThing(t));\par ??                \cf1 return\cf0  fake;\par ??            \});\par ??    \}\par ??\par ??    \cf1 internal\cf0  \cf4 IList\cf0 &amp;lt;\cf4 Thing\cf0 &amp;gt; Things \{ \cf1 get\cf0 ; \cf1 private\cf0  \cf1 set\cf0 ; \}\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;internal&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClassFixture&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;internal&lt;/span&gt; MyClassFixture()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Things
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Register&amp;lt;&lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt;&amp;gt;(()
=&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; fake
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FakeMyInterface&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.Things.ToList().ForEach(t
=&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; fake.AddThing(t));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; fake;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;internal&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IList&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Thing&lt;/span&gt;&amp;gt;
Things { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;set&lt;/span&gt;;
}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice how I've moved the IMyInterface-to-FakeMyInterface mapping to MyClassFixture.
Whenever it's asked to create a new instance of IMyInterface, MyClassFixture makes
sure to add all the Thing instances to the fake before returning it.
&lt;/p&gt;
&lt;p&gt;
Compared to the former Fixture Object of 19 lines, that's another 58% improvement.
Considering some of the APIs I encounter in my daily work, the above example is even
rather simple. The more complex and demanding your SUT's API is, the greater the gain
from using AutoFixture will be, since it's going to figure out much of the routine
stuff for you.
&lt;/p&gt;
&lt;p&gt;
With this post, I hope I have given you a taste of the power that AutoFixture provides.
It allows you to focus on specifying the behavior of your SUT, while taking care of
all the infrastructure tedium that tends to get in the way.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ef5bab91-8b41-4cc5-9e44-f6accd855d64" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,ef5bab91-8b41-4cc5-9e44-f6accd855d64.aspx</comments>
      <category>AutoFixture</category>
      <category>Productivity</category>
      <category>Unit Testing</category>
    </item>
  </channel>
</rss>