<?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, 30 Aug 2010 20:06:58 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=c74831e1-bdee-43a4-9db8-a462d84d9ec6</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,c74831e1-bdee-43a4-9db8-a462d84d9ec6.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,c74831e1-bdee-43a4-9db8-a462d84d9ec6.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=c74831e1-bdee-43a4-9db8-a462d84d9ec6</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
There still seems to be some confusion about what is <em>Dependency Injection</em> (DI)
and what is a <em>DI Container</em>, so in this post I will try to sort it out as
explicitly as possible.
</p>
        <blockquote>
          <p>
DI is a set of principles and patterns that enable loose coupling.
</p>
        </blockquote>
        <p>
That’s it; nothing else. Remember that old quote from p. 18 of <a href="http://en.wikipedia.org/wiki/Design_Patterns_%28book%29">Design
Patterns</a>?
</p>
        <blockquote>
          <p>
            <em>Program to an interface; not an implementation.</em>
          </p>
        </blockquote>
        <p>
This is the concern that DI addresses. The most useful DI pattern is <em>Constructor
Injection</em> where we inject dependencies into consumers via their constructors.
No container is required to do this.
</p>
        <p>
The easiest way to build a DI-friendly application is to just use Constructor Injection
all the way. Conversely, <em>an application does not automatically become loosely
coupled when we use a DI Container</em>. Every time application code <em>queries</em> a
container we have an instance of the <a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx">Service
Locator anti-pattern</a>. The corollary leads to this variation of the <a href="http://en.wikipedia.org/wiki/Hollywood_Principle">Hollywood
Principle</a>:
</p>
        <blockquote>
          <p>
Don’t call the container; it’ll call you.
</p>
        </blockquote>
        <p>
A DI Container is a fantastic tool. It’s like a (motorized) mixer: you can whip cream
by hand, but it’s easier with a mixer. On the other hand, without the cream the mixer
is nothing. The same is true for a DI Container: to really be valuable, your code
must employ Constructor Injection so that the container can <em>auto-wire</em> dependencies.
</p>
        <p>
A well-designed application adheres to the Hollywood Principle for DI Containers:
it doesn’t call the container. On the other hand, we can use the container to compose
the application – or we can do it the hard way; this is called <em>Poor Man’s DI</em>.
Here’s an example that uses Poor Man’s DI to compose a complete application graph
in a console application:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 private\cf0  \cf1 static\cf0  \cf1 void\cf0  Main(\cf1 string\cf0 [] args)\par \{\par     \cf1 var\cf0  msgWriter = \cf1 new\cf0  \cf2 ConsoleMessageWriter\cf0 ();\par     \cf1 new\cf0  \cf2 CoalescingParserSelector\cf0 (\par         \cf1 new\cf0  \cf2 IParser\cf0 []\par         \{\par             \cf1 new\cf0  \cf2 HelpParser\cf0 (msgWriter),\par             \cf1 new\cf0  \cf2 WineInformationParser\cf0 (\par                 \cf1 new\cf0  \cf2 SqlWineRepository\cf0 (),\par                 msgWriter)\par         \})\par         .Parse(args)\par         .CreateCommand()\par         .Execute();\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Main(<span style="color: blue">string</span>[]
args)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> msgWriter
= <span style="color: blue">new</span><span style="color: #2b91af">ConsoleMessageWriter</span>();</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">CoalescingParserSelector</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">IParser</span>[]</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">HelpParser</span>(msgWriter),</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">WineInformationParser</span>(</pre>
          <pre style="margin: 0px">                <span style="color: blue">new</span><span style="color: #2b91af">SqlWineRepository</span>(),</pre>
          <pre style="margin: 0px">                msgWriter)</pre>
          <pre style="margin: 0px">        })</pre>
          <pre style="margin: 0px">        .Parse(args)</pre>
          <pre style="margin: 0px">        .CreateCommand()</pre>
          <pre style="margin: 0px">        .Execute();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice how the nested structure of all the dependencies gives you an almost visual
idea about the graph. What we have here is Constructor Injection all the way in.
</p>
        <p>
CoalescingParserSelector’s constructor takes an IEnumerable&lt;IParser&gt; as input.
Both HelpParser and WineInformationParser requires an IMessageWriter, and WineInformationParser
also an IWineRepository. We even pull in types from different assemblies because SqlWineRepository
is defined in the SQL Server-based data access assembly.
</p>
        <p>
Another thing to notice is that the <em>msgWriter</em> variable is shared among two
consumers. This is what a DI Container normally addresses with its ability to manage <em>component
lifetime</em>. Although there’s not a DI Container in sight, we could certainly benefit
from one. Let’s try to wire up the same graph using <a href="http://unity.codeplex.com/">Unity</a> (just
for kicks):
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 private\cf0  \cf1 static\cf0  \cf1 void\cf0  Main(\cf1 string\cf0 [] args)\par \{\par     \cf1 var\cf0  container = \cf1 new\cf0  \cf2 UnityContainer\cf0 ();\par     container.RegisterType&lt;\cf2 IParser\cf0 , \cf2 WineInformationParser\cf0 &gt;(\cf3 "parser.info"\cf0 );\par     container.RegisterType&lt;\cf2 IParser\cf0 , \cf2 HelpParser\cf0 &gt;(\cf3 "parser.help"\cf0 );\par     container.RegisterType&lt;\cf2 IEnumerable\cf0 &lt;\cf2 IParser\cf0 &gt;, \cf2 IParser\cf0 []&gt;();\par \par     container.RegisterType&lt;\cf2 IParseService\cf0 , \cf2 CoalescingParserSelector\cf0 &gt;();\par \par     container.RegisterType&lt;\cf2 IWineRepository\cf0 , \cf2 SqlWineRepository\cf0 &gt;();\par     container.RegisterType&lt;\cf2 IMessageWriter\cf0 , \cf2 ConsoleMessageWriter\cf0 &gt;(\par         \cf1 new\cf0  \cf2 ContainerControlledLifetimeManager\cf0 ());\par \par     container.Resolve&lt;\cf2 IParseService\cf0 &gt;()\par         .Parse(args)\par         .CreateCommand()\par         .Execute();\par     container.Dispose();\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Main(<span style="color: blue">string</span>[]
args)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">UnityContainer</span>();</pre>
          <pre style="margin: 0px">    container.RegisterType&lt;<span style="color: #2b91af">IParser</span>, <span style="color: #2b91af">WineInformationParser</span>&gt;(<span style="color: #a31515">"parser.info"</span>);</pre>
          <pre style="margin: 0px">    container.RegisterType&lt;<span style="color: #2b91af">IParser</span>, <span style="color: #2b91af">HelpParser</span>&gt;(<span style="color: #a31515">"parser.help"</span>);</pre>
          <pre style="margin: 0px">    container.RegisterType&lt;<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">IParser</span>&gt;, <span style="color: #2b91af">IParser</span>[]&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    container.RegisterType&lt;<span style="color: #2b91af">IParseService</span>, <span style="color: #2b91af">CoalescingParserSelector</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    container.RegisterType&lt;<span style="color: #2b91af">IWineRepository</span>, <span style="color: #2b91af">SqlWineRepository</span>&gt;();</pre>
          <pre style="margin: 0px">    container.RegisterType&lt;<span style="color: #2b91af">IMessageWriter</span>, <span style="color: #2b91af">ConsoleMessageWriter</span>&gt;(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">ContainerControlledLifetimeManager</span>());</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    container.Resolve&lt;<span style="color: #2b91af">IParseService</span>&gt;()</pre>
          <pre style="margin: 0px">        .Parse(args)</pre>
          <pre style="margin: 0px">        .CreateCommand()</pre>
          <pre style="margin: 0px">        .Execute();</pre>
          <pre style="margin: 0px">    container.Dispose();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
We are using Constructor Injection throughout, and most DI Containers (even Unity,
but not <a href="http://mef.codeplex.com/">MEF</a>) natively understands that pattern.
Consequently, this means that we can mostly just map interfaces to concrete types
and the container will figure out the rest for us.
</p>
        <p>
Notice that I’m using the <a href="http://kozmic.pl/archive/2010/06/20/how-i-use-inversion-of-control-containers.aspx">Configure-Resolve-Release
pattern</a> described by <a href="http://kozmic.pl">Krzysztof Koźmic</a>. First I
configure the container, then I resolve<em> the entire object graph</em>, and lastly
I dispose the container.
</p>
        <p>
The main part of the application’s execution time will be spent within the Execute
method, which is where all the real application code runs.
</p>
        <p>
In this example I wire up a console application, but it just as well might be any
other type of application. In a web application we just do a resolve per web request
instead.
</p>
        <p>
But wait! does that mean that we have to resolve the <em>entire</em> object graph
of the application, even if we have dependencies that cannot be resolved at run-time?
No, but that does not mean that you should pull from the container. <a href="http://kozmic.pl/archive/2010/06/22/how-i-use-inversion-of-control-containers-ndash-pulling-from.aspx">Pull
from an Abstract Factory instead</a>.
</p>
        <p>
Another question that is likely to arise is: <em>what if I have dependencies that
I rarely use? Must I wire these prematurely, even if they are expensive?</em> No, <a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx">you
don’t have to do that either</a>.
</p>
        <p>
In conclusion: there is never any reason to query the container. Use a container to
compose your object graph, but don’t rely on it by querying from it. Constructor Injection
all the way enables most containers to auto-wire your application, and an <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern">Abstract
Factory</a> can be a dependency too.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=c74831e1-bdee-43a4-9db8-a462d84d9ec6" />
      </body>
      <title>Don’t call the container; it’ll call you</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,c74831e1-bdee-43a4-9db8-a462d84d9ec6.aspx</guid>
      <link>http://blog.ploeh.dk/2010/08/30/DontCallTheContainerItllCallYou.aspx</link>
      <pubDate>Mon, 30 Aug 2010 20:06:58 GMT</pubDate>
      <description>&lt;p&gt;
There still seems to be some confusion about what is &lt;em&gt;Dependency Injection&lt;/em&gt; (DI)
and what is a &lt;em&gt;DI Container&lt;/em&gt;, so in this post I will try to sort it out as
explicitly as possible.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
DI is a set of principles and patterns that enable loose coupling.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
That’s it; nothing else. Remember that old quote from p. 18 of &lt;a href="http://en.wikipedia.org/wiki/Design_Patterns_%28book%29"&gt;Design
Patterns&lt;/a&gt;?
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
&lt;em&gt;Program to an interface; not an implementation.&lt;/em&gt;
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
This is the concern that DI addresses. The most useful DI pattern is &lt;em&gt;Constructor
Injection&lt;/em&gt; where we inject dependencies into consumers via their constructors.
No container is required to do this.
&lt;/p&gt;
&lt;p&gt;
The easiest way to build a DI-friendly application is to just use Constructor Injection
all the way. Conversely, &lt;em&gt;an application does not automatically become loosely
coupled when we use a DI Container&lt;/em&gt;. Every time application code &lt;em&gt;queries&lt;/em&gt; a
container we have an instance of the &lt;a href="http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx"&gt;Service
Locator anti-pattern&lt;/a&gt;. The corollary leads to this variation of the &lt;a href="http://en.wikipedia.org/wiki/Hollywood_Principle"&gt;Hollywood
Principle&lt;/a&gt;:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Don’t call the container; it’ll call you.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
A DI Container is a fantastic tool. It’s like a (motorized) mixer: you can whip cream
by hand, but it’s easier with a mixer. On the other hand, without the cream the mixer
is nothing. The same is true for a DI Container: to really be valuable, your code
must employ Constructor Injection so that the container can &lt;em&gt;auto-wire&lt;/em&gt; dependencies.
&lt;/p&gt;
&lt;p&gt;
A well-designed application adheres to the Hollywood Principle for DI Containers:
it doesn’t call the container. On the other hand, we can use the container to compose
the application – or we can do it the hard way; this is called &lt;em&gt;Poor Man’s DI&lt;/em&gt;.
Here’s an example that uses Poor Man’s DI to compose a complete application graph
in a console application:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 private\cf0  \cf1 static\cf0  \cf1 void\cf0  Main(\cf1 string\cf0 [] args)\par \{\par     \cf1 var\cf0  msgWriter = \cf1 new\cf0  \cf2 ConsoleMessageWriter\cf0 ();\par     \cf1 new\cf0  \cf2 CoalescingParserSelector\cf0 (\par         \cf1 new\cf0  \cf2 IParser\cf0 []\par         \{\par             \cf1 new\cf0  \cf2 HelpParser\cf0 (msgWriter),\par             \cf1 new\cf0  \cf2 WineInformationParser\cf0 (\par                 \cf1 new\cf0  \cf2 SqlWineRepository\cf0 (),\par                 msgWriter)\par         \})\par         .Parse(args)\par         .CreateCommand()\par         .Execute();\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;private&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;/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; msgWriter
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ConsoleMessageWriter&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;CoalescingParserSelector&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;IParser&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;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;HelpParser&lt;/span&gt;(msgWriter),&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;WineInformationParser&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;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SqlWineRepository&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; msgWriter)&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; .Parse(args)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateCommand()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Execute();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice how the nested structure of all the dependencies gives you an almost visual
idea about the graph. What we have here is Constructor Injection all the way in.
&lt;/p&gt;
&lt;p&gt;
CoalescingParserSelector’s constructor takes an IEnumerable&amp;lt;IParser&amp;gt; as input.
Both HelpParser and WineInformationParser requires an IMessageWriter, and WineInformationParser
also an IWineRepository. We even pull in types from different assemblies because SqlWineRepository
is defined in the SQL Server-based data access assembly.
&lt;/p&gt;
&lt;p&gt;
Another thing to notice is that the &lt;em&gt;msgWriter&lt;/em&gt; variable is shared among two
consumers. This is what a DI Container normally addresses with its ability to manage &lt;em&gt;component
lifetime&lt;/em&gt;. Although there’s not a DI Container in sight, we could certainly benefit
from one. Let’s try to wire up the same graph using &lt;a href="http://unity.codeplex.com/"&gt;Unity&lt;/a&gt; (just
for kicks):
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 private\cf0  \cf1 static\cf0  \cf1 void\cf0  Main(\cf1 string\cf0 [] args)\par \{\par     \cf1 var\cf0  container = \cf1 new\cf0  \cf2 UnityContainer\cf0 ();\par     container.RegisterType&amp;lt;\cf2 IParser\cf0 , \cf2 WineInformationParser\cf0 &amp;gt;(\cf3 "parser.info"\cf0 );\par     container.RegisterType&amp;lt;\cf2 IParser\cf0 , \cf2 HelpParser\cf0 &amp;gt;(\cf3 "parser.help"\cf0 );\par     container.RegisterType&amp;lt;\cf2 IEnumerable\cf0 &amp;lt;\cf2 IParser\cf0 &amp;gt;, \cf2 IParser\cf0 []&amp;gt;();\par \par     container.RegisterType&amp;lt;\cf2 IParseService\cf0 , \cf2 CoalescingParserSelector\cf0 &amp;gt;();\par \par     container.RegisterType&amp;lt;\cf2 IWineRepository\cf0 , \cf2 SqlWineRepository\cf0 &amp;gt;();\par     container.RegisterType&amp;lt;\cf2 IMessageWriter\cf0 , \cf2 ConsoleMessageWriter\cf0 &amp;gt;(\par         \cf1 new\cf0  \cf2 ContainerControlledLifetimeManager\cf0 ());\par \par     container.Resolve&amp;lt;\cf2 IParseService\cf0 &amp;gt;()\par         .Parse(args)\par         .CreateCommand()\par         .Execute();\par     container.Dispose();\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;private&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;/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; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;UnityContainer&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IParser&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;WineInformationParser&lt;/span&gt;&amp;gt;(&lt;span style="color: #a31515"&gt;"parser.info"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IParser&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;HelpParser&lt;/span&gt;&amp;gt;(&lt;span style="color: #a31515"&gt;"parser.help"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IParser&lt;/span&gt;&amp;gt;, &lt;span style="color: #2b91af"&gt;IParser&lt;/span&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; container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IParseService&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;CoalescingParserSelector&lt;/span&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; container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IWineRepository&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;SqlWineRepository&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.RegisterType&amp;lt;&lt;span style="color: #2b91af"&gt;IMessageWriter&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;ConsoleMessageWriter&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;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ContainerControlledLifetimeManager&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; container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IParseService&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; .Parse(args)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .CreateCommand()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Execute();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Dispose();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We are using Constructor Injection throughout, and most DI Containers (even Unity,
but not &lt;a href="http://mef.codeplex.com/"&gt;MEF&lt;/a&gt;) natively understands that pattern.
Consequently, this means that we can mostly just map interfaces to concrete types
and the container will figure out the rest for us.
&lt;/p&gt;
&lt;p&gt;
Notice that I’m using the &lt;a href="http://kozmic.pl/archive/2010/06/20/how-i-use-inversion-of-control-containers.aspx"&gt;Configure-Resolve-Release
pattern&lt;/a&gt; described by &lt;a href="http://kozmic.pl"&gt;Krzysztof Koźmic&lt;/a&gt;. First I
configure the container, then I resolve&lt;em&gt; the entire object graph&lt;/em&gt;, and lastly
I dispose the container.
&lt;/p&gt;
&lt;p&gt;
The main part of the application’s execution time will be spent within the Execute
method, which is where all the real application code runs.
&lt;/p&gt;
&lt;p&gt;
In this example I wire up a console application, but it just as well might be any
other type of application. In a web application we just do a resolve per web request
instead.
&lt;/p&gt;
&lt;p&gt;
But wait! does that mean that we have to resolve the &lt;em&gt;entire&lt;/em&gt; object graph
of the application, even if we have dependencies that cannot be resolved at run-time?
No, but that does not mean that you should pull from the container. &lt;a href="http://kozmic.pl/archive/2010/06/22/how-i-use-inversion-of-control-containers-ndash-pulling-from.aspx"&gt;Pull
from an Abstract Factory instead&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Another question that is likely to arise is: &lt;em&gt;what if I have dependencies that
I rarely use? Must I wire these prematurely, even if they are expensive?&lt;/em&gt; No, &lt;a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx"&gt;you
don’t have to do that either&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
In conclusion: there is never any reason to query the container. Use a container to
compose your object graph, but don’t rely on it by querying from it. Constructor Injection
all the way enables most containers to auto-wire your application, and an &lt;a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern"&gt;Abstract
Factory&lt;/a&gt; can be a dependency too.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=c74831e1-bdee-43a4-9db8-a462d84d9ec6" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,c74831e1-bdee-43a4-9db8-a462d84d9ec6.aspx</comments>
      <category>Dependency Injection</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=04e16504-8926-45bc-9aee-6b44d9635c5d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,04e16504-8926-45bc-9aee-6b44d9635c5d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,04e16504-8926-45bc-9aee-6b44d9635c5d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=04e16504-8926-45bc-9aee-6b44d9635c5d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of my Twitter followers who appears to be using <a href="http://autofixture.codeplex.com/">AutoFixture</a> recently <a href="http://twitter.com/ZeroBugBounce/status/22007039917">asked
me this</a>:
</p>
        <blockquote>
          <p>
So with the AutoMoqCustomization I feel like I should get Mocks with concrete types
too (except the sut) - why am I wrong?
</p>
        </blockquote>
        <p>
AutoFixture’s extention for <a href="http://blog.ploeh.dk/2010/08/19/AutoFixtureAsAnAutomockingContainer.aspx">auto-mocking
with Moq</a> was never meant as a general modification of behavior. Customizations <em>extend</em> the
behavior of AutoFixture; they don’t change it. There’s a subtle difference. In any
case, the auto-mocking customization was always meant as a fallback mechanism that
would create Mocks for interfaces and abstract types because AutoFixture doesn’t know
how to deal with those.
</p>
        <p>
Apparently <a href="http://twitter.com/ZeroBugBounce">@ZeroBugBounce</a> also want
concrete classes to be issued as Mock instances, which is not quite the same thing;
AutoFixture already has a strategy for that (it’s called ConstructorInvoker).
</p>
        <p>
Nevertheless I decided to spike a little on this to see if I could get it working.
It turns out I needed to open some of the auto-mocking classes a bit for extensibility
(always a good thing), so the following doesn’t work with AutoFixture 2.0 beta 1,
but will probably work with the RTW. Also please not that I’m reporting on a spike;
I haven’t thoroughly tested all edge cases.
</p>
        <p>
That said, the first thing we need to do is to remove AutoFixture’s default ConstructorInvoker
that invokes the constructor of concrete classes. This is possible with this constructor
overload:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  Fixture(\cf2 DefaultRelays\cf0  engineParts)\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> Fixture(<span style="color: #2b91af">DefaultRelays</span> engineParts)</pre>
        </div>
        <p>
This takes as input a DefaultRelays instance, which is more or less just an IEnumerable&lt;ISpecimenBuilder&gt;
(the basic building block of AutoFixture). We need to replace that with a filter that
removes the ConstructorInvoker. Here’s a derived class that does that:
</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 FilteringRelays\cf0  : \cf2 DefaultEngineParts\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 Func\cf0 &lt;\cf2 ISpecimenBuilder\cf0 , \cf1 bool\cf0 &gt; spec;\par \par     \cf1 public\cf0  FilteringRelays(\cf2 Func\cf0 &lt;\cf2 ISpecimenBuilder\cf0 , \cf1 bool\cf0 &gt; specification)\par     \{\par         \cf1 if\cf0  (specification == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "specification"\cf0 );\par         \}\par \par         \cf1 this\cf0 .spec = specification;\par     \}\par \par     \cf1 public\cf0  \cf1 override\cf0  \cf2 IEnumerator\cf0 &lt;\cf2 ISpecimenBuilder\cf0 &gt; GetEnumerator()\par     \{\par         \cf1 var\cf0  enumerator = \cf1 base\cf0 .GetEnumerator();\par         \cf1 while\cf0  (enumerator.MoveNext())\par         \{\par             \cf1 if\cf0  (\cf1 this\cf0 .spec(enumerator.Current))\par             \{\par                 \cf1 yield\cf0  \cf1 return\cf0  enumerator.Current;\par             \}\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">FilteringRelays</span> : <span style="color: #2b91af">DefaultEngineParts</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">Func</span>&lt;<span style="color: #2b91af">ISpecimenBuilder</span>, <span style="color: blue">bool</span>&gt;
spec;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> FilteringRelays(<span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">ISpecimenBuilder</span>, <span style="color: blue">bool</span>&gt;
specification)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (specification
== <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">"specification"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.spec
= specification;</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">override</span><span style="color: #2b91af">IEnumerator</span>&lt;<span style="color: #2b91af">ISpecimenBuilder</span>&gt;
GetEnumerator()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> enumerator
= <span style="color: blue">base</span>.GetEnumerator();</pre>
          <pre style="margin: 0px">        <span style="color: blue">while</span> (enumerator.MoveNext())</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">if</span> (<span style="color: blue">this</span>.spec(enumerator.Current))</pre>
          <pre style="margin: 0px">            {</pre>
          <pre style="margin: 0px">                <span style="color: blue">yield</span><span style="color: blue">return</span> enumerator.Current;</pre>
          <pre style="margin: 0px">            }</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
DefaultEngineParts already derive from DefaultRelays, so this enables us to use the
overloaded constructor to remove the ConstructorInvoker by using these filtered relays:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;}\f0 \fs19 \cf1 Func\cf0 &lt;\cf1 ISpecimenBuilder\cf0 , \cf2 bool\cf0 &gt; concreteFilter\par     = sb =&gt; !(sb \cf2 is\cf0  \cf1 ConstructorInvoker\cf0 );\par \cf2 var\cf0  relays = \cf2 new\cf0  \cf1 FilteringRelays\cf0 (concreteFilter);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">ISpecimenBuilder</span>, <span style="color: blue">bool</span>&gt;
concreteFilter</pre>
          <pre style="margin: 0px">    = sb =&gt; !(sb <span style="color: blue">is</span><span style="color: #2b91af">ConstructorInvoker</span>);</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> relays
= <span style="color: blue">new</span><span style="color: #2b91af">FilteringRelays</span>(concreteFilter);</pre>
        </div>
        <p>
The second thing we need to do is to tell the AutoMoqCustomization that it should
Mock <em>all</em> types, not just interfaces and abstract classes. With the new (not
in beta 1) overload of the constructor, we can now supply a <a href="http://en.wikipedia.org/wiki/Specification_pattern">Specification</a> that
determines which types should be mocked.:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;}\f0 \fs19 \cf1 Func\cf0 &lt;\cf1 Type\cf0 , \cf2 bool\cf0 &gt; mockSpec = t =&gt; \cf2 true\cf0 ;\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: blue">bool</span>&gt;
mockSpec = t =&gt; <span style="color: blue">true</span>;</pre>
        </div>
        <p>
We can now create the Fixture like this to get auto-mocking of all types:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  fixture = \cf1 new\cf0  \cf2 Fixture\cf0 (relays).Customize(\par     \cf1 new\cf0  \cf2 AutoMoqCustomization\cf0 (\cf1 new\cf0  \cf2 MockRelay\cf0 (mockSpec)));\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>(relays).Customize(</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">AutoMoqCustomization</span>(<span style="color: blue">new</span><span style="color: #2b91af">MockRelay</span>(mockSpec)));</pre>
        </div>
        <p>
With this Fixture instance, we can now create concrete classes that are mocked. Here’s
the full test that proves it:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;}\f0 \fs19 [\cf1 Fact\cf0 ]\par \cf2 public\cf0  \cf2 void\cf0  CreateAnonymousMockOfConcreteType()\par \{\par     \cf3 // Fixture setup\cf0 \par     \cf1 Func\cf0 &lt;\cf1 ISpecimenBuilder\cf0 , \cf2 bool\cf0 &gt; concreteFilter\par         = sb =&gt; !(sb \cf2 is\cf0  \cf1 ConstructorInvoker\cf0 );\par     \cf2 var\cf0  relays = \cf2 new\cf0  \cf1 FilteringRelays\cf0 (concreteFilter);\par \par     \cf1 Func\cf0 &lt;\cf1 Type\cf0 , \cf2 bool\cf0 &gt; mockSpec = t =&gt; \cf2 true\cf0 ;\par \par     \cf2 var\cf0  fixture = \cf2 new\cf0  \cf1 Fixture\cf0 (relays).Customize(\par         \cf2 new\cf0  \cf1 AutoMoqCustomization\cf0 (\cf2 new\cf0  \cf1 MockRelay\cf0 (mockSpec)));\par     \cf3 // Exercise system\cf0 \par     \cf2 var\cf0  foo = fixture.CreateAnonymous&lt;\cf1 Foo\cf0 &gt;();\par     foo.DoIt();\par     \cf3 // Verify outcome\cf0 \par     \cf2 var\cf0  fooTD = \cf1 Mock\cf0 .Get(foo);\par     fooTD.Verify(f =&gt; f.DoIt());\par     \cf3 // Teardown\cf0 \par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">Fact</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> CreateAnonymousMockOfConcreteType()</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">Func</span>&lt;<span style="color: #2b91af">ISpecimenBuilder</span>, <span style="color: blue">bool</span>&gt;
concreteFilter</pre>
          <pre style="margin: 0px">        = sb =&gt; !(sb <span style="color: blue">is</span><span style="color: #2b91af">ConstructorInvoker</span>);</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> relays
= <span style="color: blue">new</span><span style="color: #2b91af">FilteringRelays</span>(concreteFilter);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Func</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: blue">bool</span>&gt;
mockSpec = t =&gt; <span style="color: blue">true</span>;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">Fixture</span>(relays).Customize(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">AutoMoqCustomization</span>(<span style="color: blue">new</span><span style="color: #2b91af">MockRelay</span>(mockSpec)));</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> foo
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Foo</span>&gt;();</pre>
          <pre style="margin: 0px">    foo.DoIt();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> fooTD
= <span style="color: #2b91af">Mock</span>.Get(foo);</pre>
          <pre style="margin: 0px">    fooTD.Verify(f =&gt; f.DoIt());</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Foo is this concrete class:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Foo\cf0 \par \{\par     \cf1 public\cf0  \cf1 virtual\cf0  \cf1 void\cf0  DoIt()\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">Foo</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">virtual</span><span style="color: blue">void</span> DoIt()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Finally, a word of caution: this is a <em>spike</em>. It’s not fully tested and is
bound to fail in certain cases: at least one case is when the type to be created is
sealed. Since <a href="http://code.google.com/p/moq/">Moq</a> can’t create a Mock
of a sealed type, the above code will fail in that case. However, we can address this
issue with some more sophisticated filters and Specifications. However, I will leave
that up to the interested reader (or a later blog post).
</p>
        <p>
All in all I think this provides an excellent glimpse of the degree of extensibility
that is built into AutoFixture 2.0’s kernel.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=04e16504-8926-45bc-9aee-6b44d9635c5d" />
      </body>
      <title>Changing the behavior of AutoFixture auto-mocking with Moq</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,04e16504-8926-45bc-9aee-6b44d9635c5d.aspx</guid>
      <link>http://blog.ploeh.dk/2010/08/25/ChangingTheBehaviorOfAutoFixtureAutomockingWithMoq.aspx</link>
      <pubDate>Wed, 25 Aug 2010 19:56:38 GMT</pubDate>
      <description>&lt;p&gt;
One of my Twitter followers who appears to be using &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; recently &lt;a href="http://twitter.com/ZeroBugBounce/status/22007039917"&gt;asked
me this&lt;/a&gt;:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
So with the AutoMoqCustomization I feel like I should get Mocks with concrete types
too (except the sut) - why am I wrong?
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
AutoFixture’s extention for &lt;a href="http://blog.ploeh.dk/2010/08/19/AutoFixtureAsAnAutomockingContainer.aspx"&gt;auto-mocking
with Moq&lt;/a&gt; was never meant as a general modification of behavior. Customizations &lt;em&gt;extend&lt;/em&gt; the
behavior of AutoFixture; they don’t change it. There’s a subtle difference. In any
case, the auto-mocking customization was always meant as a fallback mechanism that
would create Mocks for interfaces and abstract types because AutoFixture doesn’t know
how to deal with those.
&lt;/p&gt;
&lt;p&gt;
Apparently &lt;a href="http://twitter.com/ZeroBugBounce"&gt;@ZeroBugBounce&lt;/a&gt; also want
concrete classes to be issued as Mock instances, which is not quite the same thing;
AutoFixture already has a strategy for that (it’s called ConstructorInvoker).
&lt;/p&gt;
&lt;p&gt;
Nevertheless I decided to spike a little on this to see if I could get it working.
It turns out I needed to open some of the auto-mocking classes a bit for extensibility
(always a good thing), so the following doesn’t work with AutoFixture 2.0 beta 1,
but will probably work with the RTW. Also please not that I’m reporting on a spike;
I haven’t thoroughly tested all edge cases.
&lt;/p&gt;
&lt;p&gt;
That said, the first thing we need to do is to remove AutoFixture’s default ConstructorInvoker
that invokes the constructor of concrete classes. This is possible with this constructor
overload:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  Fixture(\cf2 DefaultRelays\cf0  engineParts)\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; Fixture(&lt;span style="color: #2b91af"&gt;DefaultRelays&lt;/span&gt; engineParts)&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This takes as input a DefaultRelays instance, which is more or less just an IEnumerable&amp;lt;ISpecimenBuilder&amp;gt;
(the basic building block of AutoFixture). We need to replace that with a filter that
removes the ConstructorInvoker. Here’s a derived class that does that:
&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 FilteringRelays\cf0  : \cf2 DefaultEngineParts\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 Func\cf0 &amp;lt;\cf2 ISpecimenBuilder\cf0 , \cf1 bool\cf0 &amp;gt; spec;\par \par     \cf1 public\cf0  FilteringRelays(\cf2 Func\cf0 &amp;lt;\cf2 ISpecimenBuilder\cf0 , \cf1 bool\cf0 &amp;gt; specification)\par     \{\par         \cf1 if\cf0  (specification == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "specification"\cf0 );\par         \}\par \par         \cf1 this\cf0 .spec = specification;\par     \}\par \par     \cf1 public\cf0  \cf1 override\cf0  \cf2 IEnumerator\cf0 &amp;lt;\cf2 ISpecimenBuilder\cf0 &amp;gt; GetEnumerator()\par     \{\par         \cf1 var\cf0  enumerator = \cf1 base\cf0 .GetEnumerator();\par         \cf1 while\cf0  (enumerator.MoveNext())\par         \{\par             \cf1 if\cf0  (\cf1 this\cf0 .spec(enumerator.Current))\par             \{\par                 \cf1 yield\cf0  \cf1 return\cf0  enumerator.Current;\par             \}\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;FilteringRelays&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;DefaultEngineParts&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;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ISpecimenBuilder&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;
spec;&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; FilteringRelays(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ISpecimenBuilder&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;
specification)&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; (specification
== &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;"specification"&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;.spec
= specification;&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;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IEnumerator&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ISpecimenBuilder&lt;/span&gt;&amp;gt;
GetEnumerator()&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; enumerator
= &lt;span style="color: blue"&gt;base&lt;/span&gt;.GetEnumerator();&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; (enumerator.MoveNext())&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;.spec(enumerator.Current))&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;yield&lt;/span&gt; &lt;span style="color: blue"&gt;return&lt;/span&gt; enumerator.Current;&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;
DefaultEngineParts already derive from DefaultRelays, so this enables us to use the
overloaded constructor to remove the ConstructorInvoker by using these filtered relays:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;}\f0 \fs19 \cf1 Func\cf0 &amp;lt;\cf1 ISpecimenBuilder\cf0 , \cf2 bool\cf0 &amp;gt; concreteFilter\par     = sb =&amp;gt; !(sb \cf2 is\cf0  \cf1 ConstructorInvoker\cf0 );\par \cf2 var\cf0  relays = \cf2 new\cf0  \cf1 FilteringRelays\cf0 (concreteFilter);\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: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ISpecimenBuilder&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;
concreteFilter&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; = sb =&amp;gt; !(sb &lt;span style="color: blue"&gt;is&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ConstructorInvoker&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; relays
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FilteringRelays&lt;/span&gt;(concreteFilter);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The second thing we need to do is to tell the AutoMoqCustomization that it should
Mock &lt;em&gt;all&lt;/em&gt; types, not just interfaces and abstract classes. With the new (not
in beta 1) overload of the constructor, we can now supply a &lt;a href="http://en.wikipedia.org/wiki/Specification_pattern"&gt;Specification&lt;/a&gt; that
determines which types should be mocked.:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;}\f0 \fs19 \cf1 Func\cf0 &amp;lt;\cf1 Type\cf0 , \cf2 bool\cf0 &amp;gt; mockSpec = t =&amp;gt; \cf2 true\cf0 ;\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: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;
mockSpec = t =&amp;gt; &lt;span style="color: blue"&gt;true&lt;/span&gt;;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We can now create the Fixture like this to get auto-mocking of all types:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  fixture = \cf1 new\cf0  \cf2 Fixture\cf0 (relays).Customize(\par     \cf1 new\cf0  \cf2 AutoMoqCustomization\cf0 (\cf1 new\cf0  \cf2 MockRelay\cf0 (mockSpec)));\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; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;(relays).Customize(&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;AutoMoqCustomization&lt;/span&gt;(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MockRelay&lt;/span&gt;(mockSpec)));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With this Fixture instance, we can now create concrete classes that are mocked. Here’s
the full test that proves it:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;\red0\green128\blue0;}\f0 \fs19 [\cf1 Fact\cf0 ]\par \cf2 public\cf0  \cf2 void\cf0  CreateAnonymousMockOfConcreteType()\par \{\par     \cf3 // Fixture setup\cf0 \par     \cf1 Func\cf0 &amp;lt;\cf1 ISpecimenBuilder\cf0 , \cf2 bool\cf0 &amp;gt; concreteFilter\par         = sb =&amp;gt; !(sb \cf2 is\cf0  \cf1 ConstructorInvoker\cf0 );\par     \cf2 var\cf0  relays = \cf2 new\cf0  \cf1 FilteringRelays\cf0 (concreteFilter);\par \par     \cf1 Func\cf0 &amp;lt;\cf1 Type\cf0 , \cf2 bool\cf0 &amp;gt; mockSpec = t =&amp;gt; \cf2 true\cf0 ;\par \par     \cf2 var\cf0  fixture = \cf2 new\cf0  \cf1 Fixture\cf0 (relays).Customize(\par         \cf2 new\cf0  \cf1 AutoMoqCustomization\cf0 (\cf2 new\cf0  \cf1 MockRelay\cf0 (mockSpec)));\par     \cf3 // Exercise system\cf0 \par     \cf2 var\cf0  foo = fixture.CreateAnonymous&amp;lt;\cf1 Foo\cf0 &amp;gt;();\par     foo.DoIt();\par     \cf3 // Verify outcome\cf0 \par     \cf2 var\cf0  fooTD = \cf1 Mock\cf0 .Get(foo);\par     fooTD.Verify(f =&amp;gt; f.DoIt());\par     \cf3 // Teardown\cf0 \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: #2b91af"&gt;Fact&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; CreateAnonymousMockOfConcreteType()&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;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;ISpecimenBuilder&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;
concreteFilter&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; = sb =&amp;gt; !(sb &lt;span style="color: blue"&gt;is&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ConstructorInvoker&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; relays
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FilteringRelays&lt;/span&gt;(concreteFilter);&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;Func&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: blue"&gt;bool&lt;/span&gt;&amp;gt;
mockSpec = t =&amp;gt; &lt;span style="color: blue"&gt;true&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; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt;(relays).Customize(&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;AutoMoqCustomization&lt;/span&gt;(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MockRelay&lt;/span&gt;(mockSpec)));&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; foo
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Foo&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; foo.DoIt();&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; fooTD
= &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;.Get(foo);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fooTD.Verify(f =&amp;gt; f.DoIt());&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;
Foo is this concrete class:
&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 Foo\cf0 \par \{\par     \cf1 public\cf0  \cf1 virtual\cf0  \cf1 void\cf0  DoIt()\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;Foo&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;virtual&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; DoIt()&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;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Finally, a word of caution: this is a &lt;em&gt;spike&lt;/em&gt;. It’s not fully tested and is
bound to fail in certain cases: at least one case is when the type to be created is
sealed. Since &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; can’t create a Mock
of a sealed type, the above code will fail in that case. However, we can address this
issue with some more sophisticated filters and Specifications. However, I will leave
that up to the interested reader (or a later blog post).
&lt;/p&gt;
&lt;p&gt;
All in all I think this provides an excellent glimpse of the degree of extensibility
that is built into AutoFixture 2.0’s kernel.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=04e16504-8926-45bc-9aee-6b44d9635c5d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,04e16504-8926-45bc-9aee-6b44d9635c5d.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2479066c-c462-43db-959b-6364792cd1f5</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2479066c-c462-43db-959b-6364792cd1f5.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2479066c-c462-43db-959b-6364792cd1f5.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2479066c-c462-43db-959b-6364792cd1f5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The new internal architecture of <a href="http://autofixture.codeplex.com/">AutoFixture</a> 2.0
enables some interesting features. One of these is that it becomes easy to extend
AutoFixture to become an auto-mocking container.
</p>
        <p>
Since I personally use <a href="http://code.google.com/p/moq/">Moq</a>, the AutoFixture
2.0 .zip file includes a new assembly called Ploeh.AutoFixture.AutoMoq that includes
an auto-mocking extension that uses Moq for Test Doubles.
</p>
        <blockquote>
          <p>
Please note that AutoFixture in itself has no dependency on Moq. If you don’t want
to use Moq, you can just ignore the Ploeh.AutoFixture.AutoMoq assembly.
</p>
          <p>
Auto-mocking with AutoFixture does not have to use Moq. Although it only ships with
Moq support, it is possible to write an auto-mocking extension for a different dynamic
mock library.
</p>
        </blockquote>
        <p>
To use it, you must first add a reference to Ploeh.AutoFixture.AutoMoq. You can now
create your Fixture instance 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  fixture = \cf1 new\cf0  \cf4 Fixture\cf0 ()\par ??    .Customize(\cf1 new\cf0  \cf4 AutoMoqCustomization\cf0 ());}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <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">    .Customize(<span style="color: blue">new</span><span style="color: #2b91af">AutoMoqCustomization</span>());</pre>
        </div>
        <p>
What this does is that it adds a fallback mechanism to the fixture. If a type falls
through the normal engine without being handled, the auto-mocking extension will check
whether it is a request for an interface or abstract class. If this is so, it will <em>relay</em> the
request to a request for a Mock of the same type.
</p>
        <p>
A different part of the extension handles requests for Mocks, which ensures that the
Mock will be created and returned.
</p>
        <p>
Splitting up auto-mocking into a relay and a creational strategy for Mock objects
proper also means that we can directly request a Mock if we would like that. Even
better, we can use the built-in <a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx">Freeze
support</a> to freeze a Mock, and it will also automatically freeze the auto-mocked
instance as well (because the relay will ask for a Mock that turns out to be frozen).
</p>
        <p>
Returning to the <a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx">original
frozen pizza example</a>, we can now rewrite it 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;}??\fs20 [\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  AddWillPipeMapCorrectly()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ()\par ??        .Customize(\cf4 new\cf0  \cf3 AutoMoqCustomization\cf0 ());\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&lt;\cf3 Basket\cf0 &gt;();\par ??    \cf4 var\cf0  mapMock = fixture.Freeze&lt;\cf3 Mock\cf0 &lt;\cf3 IPizzaMap\cf0 &gt;&gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&lt;\cf3 PizzaPresenter\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 BasketPresenter\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     mapMock.Verify(m =&gt; m.Pipe(pizza, basket.Add));\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">Fact</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> AddWillPipeMapCorrectly()</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">        .Customize(<span style="color: blue">new</span><span style="color: #2b91af">AutoMoqCustomization</span>());</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> basket
= fixture.Freeze&lt;<span style="color: #2b91af">Basket</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> mapMock
= fixture.Freeze&lt;<span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">IPizzaMap</span>&gt;&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> pizza
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaPresenter</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">BasketPresenter</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.Add(pizza);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    mapMock.Verify(m =&gt; m.Pipe(pizza, basket.Add));</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice that we can simply freeze Mock&lt;IPizzaMap&gt; which also automatically freeze
the IPizzaMap instance as well. When we later create the <a href="http://xunitpatterns.com/SUT.html">SUT</a> by
requesting an anonymous BasketPresenter, IPizzaMap is already frozen in the fixture,
so the correct instance will be injected into the SUT.
</p>
        <p>
This is similar to the behavior of the <a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx">custom
FreezeMoq extension method</a> I previously described, but now this feature is baked
in.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2479066c-c462-43db-959b-6364792cd1f5" />
      </body>
      <title>AutoFixture as an auto-mocking container</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2479066c-c462-43db-959b-6364792cd1f5.aspx</guid>
      <link>http://blog.ploeh.dk/2010/08/19/AutoFixtureAsAnAutomockingContainer.aspx</link>
      <pubDate>Thu, 19 Aug 2010 19:25:50 GMT</pubDate>
      <description>&lt;p&gt;
The new internal architecture of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 2.0
enables some interesting features. One of these is that it becomes easy to extend
AutoFixture to become an auto-mocking container.
&lt;/p&gt;
&lt;p&gt;
Since I personally use &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt;, the AutoFixture
2.0 .zip file includes a new assembly called Ploeh.AutoFixture.AutoMoq that includes
an auto-mocking extension that uses Moq for Test Doubles.
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Please note that AutoFixture in itself has no dependency on Moq. If you don’t want
to use Moq, you can just ignore the Ploeh.AutoFixture.AutoMoq assembly.
&lt;/p&gt;
&lt;p&gt;
Auto-mocking with AutoFixture does not have to use Moq. Although it only ships with
Moq support, it is possible to write an auto-mocking extension for a different dynamic
mock library.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
To use it, you must first add a reference to Ploeh.AutoFixture.AutoMoq. You can now
create your Fixture instance 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  fixture = \cf1 new\cf0  \cf4 Fixture\cf0 ()\par ??    .Customize(\cf1 new\cf0  \cf4 AutoMoqCustomization\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; 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; .Customize(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;AutoMoqCustomization&lt;/span&gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What this does is that it adds a fallback mechanism to the fixture. If a type falls
through the normal engine without being handled, the auto-mocking extension will check
whether it is a request for an interface or abstract class. If this is so, it will &lt;em&gt;relay&lt;/em&gt; the
request to a request for a Mock of the same type.
&lt;/p&gt;
&lt;p&gt;
A different part of the extension handles requests for Mocks, which ensures that the
Mock will be created and returned.
&lt;/p&gt;
&lt;p&gt;
Splitting up auto-mocking into a relay and a creational strategy for Mock objects
proper also means that we can directly request a Mock if we would like that. Even
better, we can use the built-in &lt;a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx"&gt;Freeze
support&lt;/a&gt; to freeze a Mock, and it will also automatically freeze the auto-mocked
instance as well (because the relay will ask for a Mock that turns out to be frozen).
&lt;/p&gt;
&lt;p&gt;
Returning to the &lt;a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx"&gt;original
frozen pizza example&lt;/a&gt;, we can now rewrite it 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;}??\fs20 [\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  AddWillPipeMapCorrectly()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ()\par ??        .Customize(\cf4 new\cf0  \cf3 AutoMoqCustomization\cf0 ());\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&amp;lt;\cf3 Basket\cf0 &amp;gt;();\par ??    \cf4 var\cf0  mapMock = fixture.Freeze&amp;lt;\cf3 Mock\cf0 &amp;lt;\cf3 IPizzaMap\cf0 &amp;gt;&amp;gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&amp;lt;\cf3 PizzaPresenter\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 BasketPresenter\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     mapMock.Verify(m =&amp;gt; m.Pipe(pizza, basket.Add));\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;Fact&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; AddWillPipeMapCorrectly()&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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Customize(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;AutoMoqCustomization&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; basket
= fixture.Freeze&amp;lt;&lt;span style="color: #2b91af"&gt;Basket&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;var&lt;/span&gt; mapMock
= fixture.Freeze&amp;lt;&lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IPizzaMap&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;var&lt;/span&gt; pizza
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaPresenter&lt;/span&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;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;BasketPresenter&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; sut.Add(pizza);&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; mapMock.Verify(m =&amp;gt; m.Pipe(pizza, basket.Add));&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;
Notice that we can simply freeze Mock&amp;lt;IPizzaMap&amp;gt; which also automatically freeze
the IPizzaMap instance as well. When we later create the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt; by
requesting an anonymous BasketPresenter, IPizzaMap is already frozen in the fixture,
so the correct instance will be injected into the SUT.
&lt;/p&gt;
&lt;p&gt;
This is similar to the behavior of the &lt;a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx"&gt;custom
FreezeMoq extension method&lt;/a&gt; I previously described, but now this feature is baked
in.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2479066c-c462-43db-959b-6364792cd1f5" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2479066c-c462-43db-959b-6364792cd1f5.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=3b0e46a4-1566-46e8-9451-3681dac68d4d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,3b0e46a4-1566-46e8-9451-3681dac68d4d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,3b0e46a4-1566-46e8-9451-3681dac68d4d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=3b0e46a4-1566-46e8-9451-3681dac68d4d</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It gives me great pleasure to announce that <a href="http://autofixture.codeplex.com/">AutoFixture</a> 2.0
beta 1 is now <a href="http://autofixture.codeplex.com/releases/view/50304">available
for download</a>. Compared to version 1.1 AutoFixture 2.0 is implemented using a new
and much more open and extensible engine that enables many interesting scenarios.
</p>
        <p>
Despite the new engine and the vastly increased potential, the focus on version 2.0
has been to ensure that the current, known feature set was preserved.
</p>
        <p>
          <strong>What’s new?</strong>
        </p>
        <p>
While AutoFixture 2.0 introduces new features, this release is first and foremost
an upgrade to a completely new internal architecture, so the number of new releases
is limited. Never the less, the following new features are available in version 2.0:
</p>
        <ul>
          <li>
            <a href="http://autofixture.codeplex.com/workitem/1744">Support for enums</a>
          </li>
          <li>
Full <a href="http://autofixture.codeplex.com/workitem/4199">support of arrays</a></li>
          <li>
Optional <a href="http://autofixture.codeplex.com/workitem/1913">tracing</a></li>
          <li>
Improved extensibility 
</li>
          <li>
Optional auto-mocking with <a href="http://code.google.com/p/moq/">Moq</a> (implemented
as a separate, optional assembly) 
</li>
          <li>
Optional extensions for <a href="http://xunit.codeplex.com/">xUnit.net</a> (implemented
as a separate, optional assembly)</li>
        </ul>
        <p>
There are still <a href="http://autofixture.codeplex.com/workitem/list/basic">open
feature requests</a> for AutoFixture, so now that the new engine is in place I can
again focus on implementing some of the features that were too difficult to address
with the old engine.
</p>
        <p>
          <strong>Breaking changes</strong>
        </p>
        <p>
Version 2.0 introduces some breaking changes, although the fundamental API remains
recognizable.
</p>
        <ul>
          <li>
A lot of the original methods on Fixture are now extension methods on IFixture (a
new interface). The methods include CreateAnonymous&lt;T&gt;, CreateMany&lt;T&gt;
and many others, so you will need to include a using directive for Ploeh.AutoFixture
to compile the unit test code. 
</li>
          <li>
CreateMany&lt;T&gt; still returns IEnumerable&lt;T&gt;, but the return value is much
more consistently deferred. This means that in almost all cases you should instantly
stabilize the sequence by converting it to a List&lt;T&gt;, an array or similar. 
</li>
          <li>
Several methods are now deprecated in favor of new methods with better names.</li>
        </ul>
        <p>
A few methods were also removed, but only those that were already deprecated in version
1.1.
</p>
        <p>
          <strong>Roadmap</strong>
        </p>
        <p>
The general availability of beta 1 of AutoFixture 2.0 marks the beginning of a trial
period. If no new issues are reported within the next few weeks, a final version 2.0
will be released. If too many issues are reported, a new beta version may be necessary.
</p>
        <p>
Please <a href="http://autofixture.codeplex.com/workitem/list/basic">report any issues</a> you
find.
</p>
        <p>
After the release of the final version 2.0 my plan is currently to focus on the <a href="http://autofixture.codeplex.com/workitem/1650">Idioms
project</a>, although there are many other new features that might warrant my attention.
</p>
        <p>
Blog posts about the new features will also follow soon.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3b0e46a4-1566-46e8-9451-3681dac68d4d" />
      </body>
      <title>AutoFixture 2.0 beta 1</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,3b0e46a4-1566-46e8-9451-3681dac68d4d.aspx</guid>
      <link>http://blog.ploeh.dk/2010/08/09/AutoFixture20Beta1.aspx</link>
      <pubDate>Mon, 09 Aug 2010 11:32:06 GMT</pubDate>
      <description>&lt;p&gt;
It gives me great pleasure to announce that &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 2.0
beta 1 is now &lt;a href="http://autofixture.codeplex.com/releases/view/50304"&gt;available
for download&lt;/a&gt;. Compared to version 1.1 AutoFixture 2.0 is implemented using a new
and much more open and extensible engine that enables many interesting scenarios.
&lt;/p&gt;
&lt;p&gt;
Despite the new engine and the vastly increased potential, the focus on version 2.0
has been to ensure that the current, known feature set was preserved.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;What’s new?&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
While AutoFixture 2.0 introduces new features, this release is first and foremost
an upgrade to a completely new internal architecture, so the number of new releases
is limited. Never the less, the following new features are available in version 2.0:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
&lt;a href="http://autofixture.codeplex.com/workitem/1744"&gt;Support for enums&lt;/a&gt; 
&lt;li&gt;
Full &lt;a href="http://autofixture.codeplex.com/workitem/4199"&gt;support of arrays&lt;/a&gt; 
&lt;li&gt;
Optional &lt;a href="http://autofixture.codeplex.com/workitem/1913"&gt;tracing&lt;/a&gt; 
&lt;li&gt;
Improved extensibility 
&lt;li&gt;
Optional auto-mocking with &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; (implemented
as a separate, optional assembly) 
&lt;li&gt;
Optional extensions for &lt;a href="http://xunit.codeplex.com/"&gt;xUnit.net&lt;/a&gt; (implemented
as a separate, optional assembly)&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
There are still &lt;a href="http://autofixture.codeplex.com/workitem/list/basic"&gt;open
feature requests&lt;/a&gt; for AutoFixture, so now that the new engine is in place I can
again focus on implementing some of the features that were too difficult to address
with the old engine.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Breaking changes&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Version 2.0 introduces some breaking changes, although the fundamental API remains
recognizable.
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
A lot of the original methods on Fixture are now extension methods on IFixture (a
new interface). The methods include CreateAnonymous&amp;lt;T&amp;gt;, CreateMany&amp;lt;T&amp;gt;
and many others, so you will need to include a using directive for Ploeh.AutoFixture
to compile the unit test code. 
&lt;li&gt;
CreateMany&amp;lt;T&amp;gt; still returns IEnumerable&amp;lt;T&amp;gt;, but the return value is much
more consistently deferred. This means that in almost all cases you should instantly
stabilize the sequence by converting it to a List&amp;lt;T&amp;gt;, an array or similar. 
&lt;li&gt;
Several methods are now deprecated in favor of new methods with better names.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
A few methods were also removed, but only those that were already deprecated in version
1.1.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Roadmap&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
The general availability of beta 1 of AutoFixture 2.0 marks the beginning of a trial
period. If no new issues are reported within the next few weeks, a final version 2.0
will be released. If too many issues are reported, a new beta version may be necessary.
&lt;/p&gt;
&lt;p&gt;
Please &lt;a href="http://autofixture.codeplex.com/workitem/list/basic"&gt;report any issues&lt;/a&gt; you
find.
&lt;/p&gt;
&lt;p&gt;
After the release of the final version 2.0 my plan is currently to focus on the &lt;a href="http://autofixture.codeplex.com/workitem/1650"&gt;Idioms
project&lt;/a&gt;, although there are many other new features that might warrant my attention.
&lt;/p&gt;
&lt;p&gt;
Blog posts about the new features will also follow soon.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3b0e46a4-1566-46e8-9451-3681dac68d4d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,3b0e46a4-1566-46e8-9451-3681dac68d4d.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=a8872a47-28ce-4726-9a53-51a620cdb4af</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=a8872a47-28ce-4726-9a53-51a620cdb4af</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://structuremap.github.com/structuremap/">StructureMap</a> offers several
different lifetimes, among these two known as <em>PerRequest</em> and <em>Unique</em> respectively.
Recently I found myself wondering what was the difference between those two, but <a href="http://twitter.com/jeremydmiller/statuses/18865954515">a</a><a href="http://twitter.com/jeremydmiller/statuses/18865987309">little</a><a href="http://twitter.com/jeremydmiller/statuses/18866005435">help</a> from <a href="http://codebetter.com/blogs/jeremy.miller/">Jeremy
Miller</a> put me on the right track.
</p>
        <p>
In short, <em>Unique</em> is equivalent to what <a href="http://castleproject.org/container/index.html">Castle
Windsor</a> calls <em>Transient:</em> every time an instance of a type is needed,
a new instance is created. Even if we need the same service multiple times in the
same resolved graph, multiple instances are created.
</p>
        <p>
          <em>PerRequest</em>, on the other hand, is a bit special. Each type can be viewed
as a <em>Singleton</em> within a single call to GetInstance, but as <em>Transient</em> across
different invocations of GetInstance. In other words, the same instance will be shared
within a resolved object graph, but if we resolve the same root type once more, we
will get a new shared instance – a <em>Singleton</em> local to that graph.
</p>
        <p>
Here are some unit tests I wrote to verify this behavior (recall that PerRequest is
StructureMap’s default lifestyle):
</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 [\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSameUniqueDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&gt;\par ??    \{\par ??        \cf4 var\cf0  unique = \cf4 new\cf0  \cf3 UniquePerRequestLifecycle\cf0 ();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().LifecycleIs(unique)\par ??            .Use&lt;\cf3 Shrimp\cf0 &gt;();\par ??        x.For&lt;\cf3 OliveOil\cf0 &gt;().LifecycleIs(unique);\par ??        x.For&lt;\cf3 EggYolk\cf0 &gt;().LifecycleIs(unique);\par ??        x.For&lt;\cf3 Vinegar\cf0 &gt;().LifecycleIs(unique);\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().LifecycleIs(unique)\par ??            .Use&lt;\cf3 Vinaigrette\cf0 &gt;();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().LifecycleIs(unique)\par ??            .Use&lt;\cf3 Mayonnaise\cf0 &gt;();\par ??        x.For&lt;\cf3 Course\cf0 &gt;().LifecycleIs(unique);\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c1.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil);\par ??\}\par ??\par ??[\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSamePerRequestDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&gt;\par ??    \{\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().Use&lt;\cf3 Shrimp\cf0 &gt;();\par ??        x.For&lt;\cf3 OliveOil\cf0 &gt;();\par ??        x.For&lt;\cf3 EggYolk\cf0 &gt;();\par ??        x.For&lt;\cf3 Vinegar\cf0 &gt;();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().Use&lt;\cf3 Vinaigrette\cf0 &gt;();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().Use&lt;\cf3 Mayonnaise\cf0 &gt;();\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??\par ??    \cf3 Assert\cf0 .Same(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c1.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .Same(\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">Fact</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ResolveServicesWithSameUniqueDependency()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">Container</span>();</pre>
          <pre style="margin: 0px">    container.Configure(x =&gt;</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> unique
= <span style="color: blue">new</span><span style="color: #2b91af">UniquePerRequestLifecycle</span>();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().LifecycleIs(unique)</pre>
          <pre style="margin: 0px">            .Use&lt;<span style="color: #2b91af">Shrimp</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">OliveOil</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">EggYolk</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">Vinegar</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().LifecycleIs(unique)</pre>
          <pre style="margin: 0px">            .Use&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().LifecycleIs(unique)</pre>
          <pre style="margin: 0px">            .Use&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">Course</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">    });</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c1
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c2
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">[<span style="color: #2b91af">Fact</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ResolveServicesWithSamePerRequestDependency()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">Container</span>();</pre>
          <pre style="margin: 0px">    container.Configure(x =&gt;</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().Use&lt;<span style="color: #2b91af">Shrimp</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">OliveOil</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">EggYolk</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">Vinegar</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().Use&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().Use&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;();</pre>
          <pre style="margin: 0px">    });</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c1
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c2
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.Same(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.Same(</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice that in both cases, the OliveOil instances are different across two independently
resolved graphs (<em>c1</em> and <em>c2</em>).
</p>
        <p>
However, within each graph, the same OliveOil instance is shared in the <em>PerRequest</em> configuration,
whereas they are different in the <em>Unique</em> configuration.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a8872a47-28ce-4726-9a53-51a620cdb4af" />
      </body>
      <title>StructureMap PerRequest vs. Unique lifetimes</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</guid>
      <link>http://blog.ploeh.dk/2010/07/20/StructureMapPerRequestVsUniqueLifetimes.aspx</link>
      <pubDate>Tue, 20 Jul 2010 20:42:53 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://structuremap.github.com/structuremap/"&gt;StructureMap&lt;/a&gt; offers several
different lifetimes, among these two known as &lt;em&gt;PerRequest&lt;/em&gt; and &lt;em&gt;Unique&lt;/em&gt; respectively.
Recently I found myself wondering what was the difference between those two, but &lt;a href="http://twitter.com/jeremydmiller/statuses/18865954515"&gt;a&lt;/a&gt; &lt;a href="http://twitter.com/jeremydmiller/statuses/18865987309"&gt;little&lt;/a&gt; &lt;a href="http://twitter.com/jeremydmiller/statuses/18866005435"&gt;help&lt;/a&gt; from &lt;a href="http://codebetter.com/blogs/jeremy.miller/"&gt;Jeremy
Miller&lt;/a&gt; put me on the right track.
&lt;/p&gt;
&lt;p&gt;
In short, &lt;em&gt;Unique&lt;/em&gt; is equivalent to what &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt; calls &lt;em&gt;Transient:&lt;/em&gt; every time an instance of a type is needed,
a new instance is created. Even if we need the same service multiple times in the
same resolved graph, multiple instances are created.
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;PerRequest&lt;/em&gt;, on the other hand, is a bit special. Each type can be viewed
as a &lt;em&gt;Singleton&lt;/em&gt; within a single call to GetInstance, but as &lt;em&gt;Transient&lt;/em&gt; across
different invocations of GetInstance. In other words, the same instance will be shared
within a resolved object graph, but if we resolve the same root type once more, we
will get a new shared instance – a &lt;em&gt;Singleton&lt;/em&gt; local to that graph.
&lt;/p&gt;
&lt;p&gt;
Here are some unit tests I wrote to verify this behavior (recall that PerRequest is
StructureMap’s default lifestyle):
&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 [\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSameUniqueDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&amp;gt;\par ??    \{\par ??        \cf4 var\cf0  unique = \cf4 new\cf0  \cf3 UniquePerRequestLifecycle\cf0 ();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().LifecycleIs(unique)\par ??            .Use&amp;lt;\cf3 Shrimp\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 OliveOil\cf0 &amp;gt;().LifecycleIs(unique);\par ??        x.For&amp;lt;\cf3 EggYolk\cf0 &amp;gt;().LifecycleIs(unique);\par ??        x.For&amp;lt;\cf3 Vinegar\cf0 &amp;gt;().LifecycleIs(unique);\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().LifecycleIs(unique)\par ??            .Use&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().LifecycleIs(unique)\par ??            .Use&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 Course\cf0 &amp;gt;().LifecycleIs(unique);\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil);\par ??\}\par ??\par ??[\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSamePerRequestDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&amp;gt;\par ??    \{\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().Use&amp;lt;\cf3 Shrimp\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 OliveOil\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 EggYolk\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 Vinegar\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().Use&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().Use&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;();\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??\par ??    \cf3 Assert\cf0 .Same(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .Same(\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil);\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: #2b91af"&gt;Fact&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; ResolveServicesWithSameUniqueDependency()&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; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Container&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Configure(x =&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;var&lt;/span&gt; unique
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;UniquePerRequestLifecycle&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().LifecycleIs(unique)&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; .Use&amp;lt;&lt;span style="color: #2b91af"&gt;Shrimp&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;OliveOil&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;EggYolk&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;Vinegar&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().LifecycleIs(unique)&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; .Use&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().LifecycleIs(unique)&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; .Use&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&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;var&lt;/span&gt; c1
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&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;var&lt;/span&gt; c2
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&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: #2b91af"&gt;Assert&lt;/span&gt;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&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;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&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;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil);&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: #2b91af"&gt;Fact&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; ResolveServicesWithSamePerRequestDependency()&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; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Container&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Configure(x =&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().Use&amp;lt;&lt;span style="color: #2b91af"&gt;Shrimp&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;OliveOil&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;EggYolk&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;Vinegar&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().Use&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&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; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().Use&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&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;var&lt;/span&gt; c1
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&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;var&lt;/span&gt; c2
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&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: #2b91af"&gt;Assert&lt;/span&gt;.Same(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&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;.Same(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&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;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that in both cases, the OliveOil instances are different across two independently
resolved graphs (&lt;em&gt;c1&lt;/em&gt; and &lt;em&gt;c2&lt;/em&gt;).
&lt;/p&gt;
&lt;p&gt;
However, within each graph, the same OliveOil instance is shared in the &lt;em&gt;PerRequest&lt;/em&gt; configuration,
whereas they are different in the &lt;em&gt;Unique&lt;/em&gt; configuration.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a8872a47-28ce-4726-9a53-51a620cdb4af" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</comments>
      <category>Dependency Injection</category>
      <category>StructureMap</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd</wfw:commentRss>
      <slash:comments>9</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Occasionally I get a question about whether it is reasonable or advisable to let domain
objects implement IDataErrorInfo. In summary, my answer is that it’s not so much a
question about whether it’s a leaky abstraction or not, but rather whether it makes
sense at all. To me, it doesn’t.
</p>
        <p>
Let us first consider the <em>essence</em> of the concept underlying IDataErrorInfo:
It provides information about the validity of an object. More specifically, it provides
error information when an object is in an <em>invalid</em> state.
</p>
        <p>
This is really the crux of the matter. Domain Objects should be designed so that they
cannot be put into invalid states. They should guarantee their invariants.
</p>
        <p>
Let us return to the good old <a href="http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx">DanishPhoneNumber
example</a>. Instead of accepting or representing a Danish phone number as a string
or integer, we model it as a Value Object that encapsulates the appropriate domain
logic.
</p>
        <p>
More specifically, the class’ constructor guarantees that you can’t create an invalid
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;\red163\green21\blue21;}??\fs20 \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par ??\par ??\cf1 public\cf0  DanishPhoneNumber(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 if\cf0  ((number &lt; 112) ||\par ??        (number &gt; 99999999))\par ??    \{\par ??        \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "number"\cf0 );\par ??    \}\par ??    \cf1 this\cf0 .number = number;\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">readonly</span>
            <span style="color: blue">int</span> number;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span> DanishPhoneNumber(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> ((number
&lt; 112) ||</pre>
          <pre style="margin: 0px">        (number &gt; 99999999))</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">"number"</span>);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.number
= number;</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice that the Guard Clause guarantees that you can’t create an instance with an
invalid number, and the readonly keyword guarantees that you can’t change the value
afterwards. Immutable types make it easier to protect a type’s invariants, but it
is also possible with mutable types – you just need to place proper Guards in public
setters and other mutators, as well as in the constructor.
</p>
        <p>
In any case, whenever a Domain Object guarantees its invariants according to the correct
domain logic it makes no sense for it to implement IDataErrorInfo; if it did, the
implementation would be trivial, because there would never be an error to report.
</p>
        <p>
Does this mean that IDataErrorInfo is a redundant interface? Not at all, but it is
important to realize that it’s an Application Boundary concern instead of a Domain
concern. At Application Boundaries, data entry errors will happen, and we must be
able to cope with them appropriately; we don’t want the application to crash by passing
unvalidated data to DanishPhoneNumber’s constructor.
</p>
        <p>
Does this mean that we should duplicate domain logic at the Application Boundary?
That should not be necessary. At first, we can apply a simple refactoring to the DanishPhoneNumber
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;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  DanishPhoneNumber(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 if\cf0  (!\cf4 DanishPhoneNumber\cf0 .IsValid(number))\par ??    \{\par ??        \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "number"\cf0 );\par ??    \}\par ??    \cf1 this\cf0 .number = number;\par ??\}\par ??\par ??\cf1 public\cf0  \cf1 static\cf0  \cf1 bool\cf0  IsValid(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 return\cf0  (112 &lt;= number)\par ??        &amp;&amp; (number &lt;= 99999999);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> DanishPhoneNumber(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (!<span style="color: #2b91af">DanishPhoneNumber</span>.IsValid(number))</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">"number"</span>);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.number
= number;</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">bool</span> IsValid(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> (112
&lt;= number)</pre>
          <pre style="margin: 0px">        &amp;&amp; (number &lt;= 99999999);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
We now have a public IsValid method we can use to implement an IDataErrorInfo at the
Application Boundary. Next steps might be to add a TryParse method.
</p>
        <p>
IDataErrorInfo implementations are often related to input forms in user interfaces.
Instead of crashing the application or closing the form, we want to provide appropriate
error messages to the user. We can use the Domain Object to provide validation logic,
but the concern is completely different: we want the form to stay open until valid
data has been entered. Not until all data is valid do we allow the creation of a Domain
Object from that data.
</p>
        <p>
In short, if you feel tempted to add IDataErrorInfo to a Domain Class, consider whether
you aren’t about to violate the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a>. In my opinion, this is the case, and you would be better
off reconsidering the design.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd" />
      </body>
      <title>Domain Objects and IDataErrorInfo</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd.aspx</guid>
      <link>http://blog.ploeh.dk/2010/07/12/DomainObjectsAndIDataErrorInfo.aspx</link>
      <pubDate>Mon, 12 Jul 2010 12:58:16 GMT</pubDate>
      <description>&lt;p&gt;
Occasionally I get a question about whether it is reasonable or advisable to let domain
objects implement IDataErrorInfo. In summary, my answer is that it’s not so much a
question about whether it’s a leaky abstraction or not, but rather whether it makes
sense at all. To me, it doesn’t.
&lt;/p&gt;
&lt;p&gt;
Let us first consider the &lt;em&gt;essence&lt;/em&gt; of the concept underlying IDataErrorInfo:
It provides information about the validity of an object. More specifically, it provides
error information when an object is in an &lt;em&gt;invalid&lt;/em&gt; state.
&lt;/p&gt;
&lt;p&gt;
This is really the crux of the matter. Domain Objects should be designed so that they
cannot be put into invalid states. They should guarantee their invariants.
&lt;/p&gt;
&lt;p&gt;
Let us return to the good old &lt;a href="http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx"&gt;DanishPhoneNumber
example&lt;/a&gt;. Instead of accepting or representing a Danish phone number as a string
or integer, we model it as a Value Object that encapsulates the appropriate domain
logic.
&lt;/p&gt;
&lt;p&gt;
More specifically, the class’ constructor guarantees that you can’t create an invalid
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;\red163\green21\blue21;}??\fs20 \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par ??\par ??\cf1 public\cf0  DanishPhoneNumber(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 if\cf0  ((number &amp;lt; 112) ||\par ??        (number &amp;gt; 99999999))\par ??    \{\par ??        \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "number"\cf0 );\par ??    \}\par ??    \cf1 this\cf0 .number = number;\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;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; number;&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; DanishPhoneNumber(&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;if&lt;/span&gt; ((number
&amp;lt; 112) ||&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; (number &amp;gt; 99999999))&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;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;"number"&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: blue"&gt;this&lt;/span&gt;.number
= number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that the Guard Clause guarantees that you can’t create an instance with an
invalid number, and the readonly keyword guarantees that you can’t change the value
afterwards. Immutable types make it easier to protect a type’s invariants, but it
is also possible with mutable types – you just need to place proper Guards in public
setters and other mutators, as well as in the constructor.
&lt;/p&gt;
&lt;p&gt;
In any case, whenever a Domain Object guarantees its invariants according to the correct
domain logic it makes no sense for it to implement IDataErrorInfo; if it did, the
implementation would be trivial, because there would never be an error to report.
&lt;/p&gt;
&lt;p&gt;
Does this mean that IDataErrorInfo is a redundant interface? Not at all, but it is
important to realize that it’s an Application Boundary concern instead of a Domain
concern. At Application Boundaries, data entry errors will happen, and we must be
able to cope with them appropriately; we don’t want the application to crash by passing
unvalidated data to DanishPhoneNumber’s constructor.
&lt;/p&gt;
&lt;p&gt;
Does this mean that we should duplicate domain logic at the Application Boundary?
That should not be necessary. At first, we can apply a simple refactoring to the DanishPhoneNumber
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;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  DanishPhoneNumber(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 if\cf0  (!\cf4 DanishPhoneNumber\cf0 .IsValid(number))\par ??    \{\par ??        \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentOutOfRangeException\cf0 (\cf5 "number"\cf0 );\par ??    \}\par ??    \cf1 this\cf0 .number = number;\par ??\}\par ??\par ??\cf1 public\cf0  \cf1 static\cf0  \cf1 bool\cf0  IsValid(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 return\cf0  (112 &amp;lt;= number)\par ??        &amp;amp;&amp;amp; (number &amp;lt;= 99999999);\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; DanishPhoneNumber(&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;if&lt;/span&gt; (!&lt;span style="color: #2b91af"&gt;DanishPhoneNumber&lt;/span&gt;.IsValid(number))&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;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;"number"&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: blue"&gt;this&lt;/span&gt;.number
= number;&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;static&lt;/span&gt; &lt;span style="color: blue"&gt;bool&lt;/span&gt; IsValid(&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;return&lt;/span&gt; (112
&amp;lt;= number)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &amp;amp;&amp;amp; (number &amp;lt;= 99999999);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We now have a public IsValid method we can use to implement an IDataErrorInfo at the
Application Boundary. Next steps might be to add a TryParse method.
&lt;/p&gt;
&lt;p&gt;
IDataErrorInfo implementations are often related to input forms in user interfaces.
Instead of crashing the application or closing the form, we want to provide appropriate
error messages to the user. We can use the Domain Object to provide validation logic,
but the concern is completely different: we want the form to stay open until valid
data has been entered. Not until all data is valid do we allow the creation of a Domain
Object from that data.
&lt;/p&gt;
&lt;p&gt;
In short, if you feel tempted to add IDataErrorInfo to a Domain Class, consider whether
you aren’t about to violate the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt;. In my opinion, this is the case, and you would be better
off reconsidering the design.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,aa79e75b-da5e-4aaa-ac8a-f6082af7b2dd.aspx</comments>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=1e9b836b-0557-4981-ab24-9e863268fa81</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,1e9b836b-0557-4981-ab24-9e863268fa81.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,1e9b836b-0557-4981-ab24-9e863268fa81.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=1e9b836b-0557-4981-ab24-9e863268fa81</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
The <a href="http://blog.ploeh.dk/2010/04/06/MappingTypesWithAutoFixture.aspx">last
time I presented a sample</a> of an <a href="http://autofixture.codeplex.com/">AutoFixture</a>-based
unit test, I purposely glossed over the state-based verification that asserted that
the resulting state of the <em>basket</em> variable was that the appropriate Pizza
was added:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;\red163\green21\blue21;}??\fs20 \cf1 Assert\cf0 .IsTrue(basket.Pizze.Any(p =&gt;\par ??    p.Name == pizza.Name), \cf4 "Basket has added pizza."\cf0 );}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">Assert</span>.IsTrue(basket.Pizze.Any(p
=&gt;</pre>
          <pre style="margin: 0px">    p.Name == pizza.Name), <span style="color: #a31515">"Basket
has added pizza."</span>);</pre>
        </div>
        <p>
The main issue with this assertion is that the implied equality expression is rather
weak: we consider a PizzaPresenter instance to be equal to a Pizza instance if their
Name properties match.
</p>
        <p>
What if they have other properties (like Size) that don’t match? If this is the case,
the test would be a <a href="http://xunitpatterns.com/false%20negative.html">false
negative</a>. A match would be found in the Pizze collection, but the instances would
not truly represent the same pizza.
</p>
        <p>
How do we resolve this conundrum without introducing <a href="http://xunitpatterns.com/Test%20Logic%20in%20Production.html#Equality%20Pollution">equality
pollution</a>? AutoFixture offers one option in the form of the generic Likeness&lt;TSource,
TDestination&gt; class. This class offers convention-based <a href="http://xunitpatterns.com/test-specific%20equality.html">test-specific
equality</a> mapping from TSource to TDestination and overriding the Equals method.
</p>
        <p>
One of the ways we can use it is by a convenience extension method. This unit test
is a refactoring of the test from the previous post, but now using Likeness:
</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  AddWillAddToBasket_Likeness()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    fixture.Register&lt;\cf3 IPizzaMap\cf0 , \cf3 PizzaMap\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&lt;\cf3 Basket\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&lt;\cf3 PizzaPresenter\cf0 &gt;();\par ??    \cf4 var\cf0  expectedPizza = \par ??        pizza.AsSource().OfLikeness&lt;\cf3 Pizza\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 BasketPresenter\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .IsTrue(basket.Pizze.Any(expectedPizza.Equals));\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> AddWillAddToBasket_Likeness()</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.Register&lt;<span style="color: #2b91af">IPizzaMap</span>, <span style="color: #2b91af">PizzaMap</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> basket
= fixture.Freeze&lt;<span style="color: #2b91af">Basket</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> pizza
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaPresenter</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> expectedPizza
= </pre>
          <pre style="margin: 0px">        pizza.AsSource().OfLikeness&lt;<span style="color: #2b91af">Pizza</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">BasketPresenter</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.Add(pizza);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.IsTrue(basket.Pizze.Any(expectedPizza.Equals));</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice how the Likeness instance is created with the AsSource() extension method.
The <em>pizza</em> instance (of type PizzaPresenter) is the source of the Likeness,
whereas the Pizza domain model type is the destination. The <em>expectedPizza</em> instance
is of type Likeness&lt;PizzaPresenter, Pizza&gt;.
</p>
        <p>
The Likeness class overrides Equals with a convention-based comparison: if two properties
have the same name and type, they are equal if their values are equal. All public
properties on the destination must have equal properties on the source.
</p>
        <p>
This allows me to specify the Equals method as the predicate for the Any method in
the assertion:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 Assert\cf0 .IsTrue(basket.Pizze.Any(expectedPizza.Equals));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">Assert</span>.IsTrue(basket.Pizze.Any(expectedPizza.Equals));</pre>
        </div>
        <p>
When the Any method evalues the Pizze collection, it executes the Equals method on
Likeness, resulting in a convention-based comparison of all public properties and
fields on the two instances.
</p>
        <p>
It’s possible to customize the comparison to override the behavior for certain properties,
but I will leave that to later posts. This post only scratches the surface of what
Likeness can do.
</p>
        <p>
To use Likeness, you must add a reference to the Ploeh.SemanticComparison assembly.
You can create a new instance using the public constructor, but to use the AsSource
extension method, you will need to add a using directive:
</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 using\cf0  Ploeh.SemanticComparison.Fluent;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">using</span> Ploeh.SemanticComparison.Fluent;</pre>
        </div>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1e9b836b-0557-4981-ab24-9e863268fa81" />
      </body>
      <title>Introducing AutoFixture Likeness</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,1e9b836b-0557-4981-ab24-9e863268fa81.aspx</guid>
      <link>http://blog.ploeh.dk/2010/06/29/IntroducingAutoFixtureLikeness.aspx</link>
      <pubDate>Tue, 29 Jun 2010 06:39:30 GMT</pubDate>
      <description>&lt;p&gt;
The &lt;a href="http://blog.ploeh.dk/2010/04/06/MappingTypesWithAutoFixture.aspx"&gt;last
time I presented a sample&lt;/a&gt; of an &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;-based
unit test, I purposely glossed over the state-based verification that asserted that
the resulting state of the &lt;em&gt;basket&lt;/em&gt; variable was that the appropriate Pizza
was added:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;\red163\green21\blue21;}??\fs20 \cf1 Assert\cf0 .IsTrue(basket.Pizze.Any(p =&amp;gt;\par ??    p.Name == pizza.Name), \cf4 "Basket has added pizza."\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;Assert&lt;/span&gt;.IsTrue(basket.Pizze.Any(p
=&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; p.Name == pizza.Name), &lt;span style="color: #a31515"&gt;"Basket
has added pizza."&lt;/span&gt;);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The main issue with this assertion is that the implied equality expression is rather
weak: we consider a PizzaPresenter instance to be equal to a Pizza instance if their
Name properties match.
&lt;/p&gt;
&lt;p&gt;
What if they have other properties (like Size) that don’t match? If this is the case,
the test would be a &lt;a href="http://xunitpatterns.com/false%20negative.html"&gt;false
negative&lt;/a&gt;. A match would be found in the Pizze collection, but the instances would
not truly represent the same pizza.
&lt;/p&gt;
&lt;p&gt;
How do we resolve this conundrum without introducing &lt;a href="http://xunitpatterns.com/Test%20Logic%20in%20Production.html#Equality%20Pollution"&gt;equality
pollution&lt;/a&gt;? AutoFixture offers one option in the form of the generic Likeness&amp;lt;TSource,
TDestination&amp;gt; class. This class offers convention-based &lt;a href="http://xunitpatterns.com/test-specific%20equality.html"&gt;test-specific
equality&lt;/a&gt; mapping from TSource to TDestination and overriding the Equals method.
&lt;/p&gt;
&lt;p&gt;
One of the ways we can use it is by a convenience extension method. This unit test
is a refactoring of the test from the previous post, but now using Likeness:
&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  AddWillAddToBasket_Likeness()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    fixture.Register&amp;lt;\cf3 IPizzaMap\cf0 , \cf3 PizzaMap\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&amp;lt;\cf3 Basket\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&amp;lt;\cf3 PizzaPresenter\cf0 &amp;gt;();\par ??    \cf4 var\cf0  expectedPizza = \par ??        pizza.AsSource().OfLikeness&amp;lt;\cf3 Pizza\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 BasketPresenter\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .IsTrue(basket.Pizze.Any(expectedPizza.Equals));\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; AddWillAddToBasket_Likeness()&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.Register&amp;lt;&lt;span style="color: #2b91af"&gt;IPizzaMap&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;PizzaMap&lt;/span&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;var&lt;/span&gt; basket
= fixture.Freeze&amp;lt;&lt;span style="color: #2b91af"&gt;Basket&lt;/span&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;var&lt;/span&gt; pizza
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaPresenter&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;var&lt;/span&gt; expectedPizza
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; pizza.AsSource().OfLikeness&amp;lt;&lt;span style="color: #2b91af"&gt;Pizza&lt;/span&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;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;BasketPresenter&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; sut.Add(pizza);&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(basket.Pizze.Any(expectedPizza.Equals));&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;
Notice how the Likeness instance is created with the AsSource() extension method.
The &lt;em&gt;pizza&lt;/em&gt; instance (of type PizzaPresenter) is the source of the Likeness,
whereas the Pizza domain model type is the destination. The &lt;em&gt;expectedPizza&lt;/em&gt; instance
is of type Likeness&amp;lt;PizzaPresenter, Pizza&amp;gt;.
&lt;/p&gt;
&lt;p&gt;
The Likeness class overrides Equals with a convention-based comparison: if two properties
have the same name and type, they are equal if their values are equal. All public
properties on the destination must have equal properties on the source.
&lt;/p&gt;
&lt;p&gt;
This allows me to specify the Equals method as the predicate for the Any method in
the assertion:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 Assert\cf0 .IsTrue(basket.Pizze.Any(expectedPizza.Equals));}
--&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;Assert&lt;/span&gt;.IsTrue(basket.Pizze.Any(expectedPizza.Equals));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
When the Any method evalues the Pizze collection, it executes the Equals method on
Likeness, resulting in a convention-based comparison of all public properties and
fields on the two instances.
&lt;/p&gt;
&lt;p&gt;
It’s possible to customize the comparison to override the behavior for certain properties,
but I will leave that to later posts. This post only scratches the surface of what
Likeness can do.
&lt;/p&gt;
&lt;p&gt;
To use Likeness, you must add a reference to the Ploeh.SemanticComparison assembly.
You can create a new instance using the public constructor, but to use the AsSource
extension method, you will need to add a using directive:
&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 using\cf0  Ploeh.SemanticComparison.Fluent;}
--&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;using&lt;/span&gt; Ploeh.SemanticComparison.Fluent;&lt;/pre&gt;
&lt;/div&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=1e9b836b-0557-4981-ab24-9e863268fa81" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,1e9b836b-0557-4981-ab24-9e863268fa81.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In the next couple of weeks I will be giving a couple of talks in Copenhagen.
</p>
        <p>
At <a href="http://communityday.in/copenhagen/Home/Agenda">Community Day 2010</a> I
will be giving two talks on respectively Dependency Injection and TDD.
</p>
        <p>
In early June I will be giving a <a href="http://www.eventbrite.com/event/660219735">repeat
of my previous CNUG TDD talk</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991" />
      </body>
      <title>Upcoming talks spring 2010</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</guid>
      <link>http://blog.ploeh.dk/2010/05/23/UpcomingTalksSpring2010.aspx</link>
      <pubDate>Sun, 23 May 2010 16:11:37 GMT</pubDate>
      <description>&lt;p&gt;
In the next couple of weeks I will be giving a couple of talks in Copenhagen.
&lt;/p&gt;
&lt;p&gt;
At &lt;a href="http://communityday.in/copenhagen/Home/Agenda"&gt;Community Day 2010&lt;/a&gt; I
will be giving two talks on respectively Dependency Injection and TDD.
&lt;/p&gt;
&lt;p&gt;
In early June I will be giving a &lt;a href="http://www.eventbrite.com/event/660219735"&gt;repeat
of my previous CNUG TDD talk&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</comments>
      <category>Dependency Injection</category>
      <category>Miscellaneous</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=f1a71969-0584-4a15-9395-9f2ac65f104b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=f1a71969-0584-4a15-9395-9f2ac65f104b</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of Castle Windsor’s facilities addresses wiring up of WCF services. So far, the
sparse documentation for the WCF Facility seems to indicate <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html">that
you have to configure your container in a global.asax</a>. That’s not much to my liking.
First of all, it reeks of ASP.NET, and secondly, it’s not going to work if you expose
WCF over protocols other than HTTP.
</p>
        <p>
However, now that we know that <a href="http://blog.ploeh.dk/2010/05/17/ServiceHostFactoryLifetime.aspx">a
custom ServiceHostFactory is effectively a Singleton</a>, a much better alternative
is to derive from the WCF Facility’s DefaultServiceHost class:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooServiceHostFactory\cf0  : \par     \cf2 DefaultServiceHostFactory\cf0 \par \{\par     \cf1 public\cf0  FooServiceHostFactory()\par         : \cf1 base\cf0 (\cf2 FooServiceHostFactory\cf0 .CreateKernel())\par     \{\par     \}\par \par     \cf1 private\cf0  \cf1 static\cf0  \cf2 IKernel\cf0  CreateKernel()\par     \{\par         \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par \par         container.AddFacility&lt;\cf2 WcfFacility\cf0 &gt;();\par \par         container.Register(\cf2 Component\cf0 \par             .For&lt;\cf2 FooService\cf0 &gt;()\par             .LifeStyle.Transient);\par         container.Register(\cf2 Component\cf0 \par             .For&lt;\cf2 IBar\cf0 &gt;()\par             .ImplementedBy&lt;\cf2 Bar\cf0 &gt;());\par \par         \cf1 return\cf0  container.Kernel;\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">FooServiceHostFactory</span> : </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">DefaultServiceHostFactory</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> FooServiceHostFactory()</pre>
          <pre style="margin: 0px">        : <span style="color: blue">base</span>(<span style="color: #2b91af">FooServiceHostFactory</span>.CreateKernel())</pre>
          <pre style="margin: 0px">    {</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">IKernel</span> CreateKernel()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        container.AddFacility&lt;<span style="color: #2b91af">WcfFacility</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">            .For&lt;<span style="color: #2b91af">FooService</span>&gt;()</pre>
          <pre style="margin: 0px">            .LifeStyle.Transient);</pre>
          <pre style="margin: 0px">        container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">            .For&lt;<span style="color: #2b91af">IBar</span>&gt;()</pre>
          <pre style="margin: 0px">            .ImplementedBy&lt;<span style="color: #2b91af">Bar</span>&gt;());</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> container.Kernel;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Although it feels a little odd to create a container and then not really use it, but
only its Kernel property, this works like a charm. It correctly wires up this FooService:
</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 FooService\cf0  : \cf2 IFooService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IBar\cf0  bar;\par \par     \cf1 public\cf0  FooService(\cf2 IBar\cf0  bar)\par     \{\par         \cf1 if\cf0  (bar == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "bar"\cf0 );\par         \}\par \par         \cf1 this\cf0 .bar = bar;\par     \}\par \par \cf1     #region\cf0  IFooService Members\par \par     \cf1 public\cf0  \cf1 string\cf0  Foo()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .bar.Baz;\par     \}\par \par \cf1     #endregion\cf0 \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">FooService</span> : <span style="color: #2b91af">IFooService</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">IBar</span> bar;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> FooService(<span style="color: #2b91af">IBar</span> bar)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (bar
== <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">"bar"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.bar
= bar;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IFooService Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">string</span> Foo()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.bar.Baz;</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>
However, instead of the static CreateKernel method that creates the IKernel instance, <a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/5401a7189f8295af/2dabe6cbb3c63488?q=">I
suggest that the WCF Facility utilizes the Factory Method pattern</a>. As the WCF
Facility has not yet been released, perhaps there’s still time for that change.
</p>
        <p>
In any case, the WCF Facility saves you from writing a lot of infrastructure code
if you would like to wire your WCF services with Castle Windsor.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f1a71969-0584-4a15-9395-9f2ac65f104b" />
      </body>
      <title>Sneak view at Castle’s WCF Facility</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</guid>
      <link>http://blog.ploeh.dk/2010/05/18/SneakViewAtCastlesWCFFacility.aspx</link>
      <pubDate>Tue, 18 May 2010 05:27:56 GMT</pubDate>
      <description>&lt;p&gt;
One of Castle Windsor’s facilities addresses wiring up of WCF services. So far, the
sparse documentation for the WCF Facility seems to indicate &lt;a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html"&gt;that
you have to configure your container in a global.asax&lt;/a&gt;. That’s not much to my liking.
First of all, it reeks of ASP.NET, and secondly, it’s not going to work if you expose
WCF over protocols other than HTTP.
&lt;/p&gt;
&lt;p&gt;
However, now that we know that &lt;a href="http://blog.ploeh.dk/2010/05/17/ServiceHostFactoryLifetime.aspx"&gt;a
custom ServiceHostFactory is effectively a Singleton&lt;/a&gt;, a much better alternative
is to derive from the WCF Facility’s DefaultServiceHost class:
&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 FooServiceHostFactory\cf0  : \par     \cf2 DefaultServiceHostFactory\cf0 \par \{\par     \cf1 public\cf0  FooServiceHostFactory()\par         : \cf1 base\cf0 (\cf2 FooServiceHostFactory\cf0 .CreateKernel())\par     \{\par     \}\par \par     \cf1 private\cf0  \cf1 static\cf0  \cf2 IKernel\cf0  CreateKernel()\par     \{\par         \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par \par         container.AddFacility&amp;lt;\cf2 WcfFacility\cf0 &amp;gt;();\par \par         container.Register(\cf2 Component\cf0 \par             .For&amp;lt;\cf2 FooService\cf0 &amp;gt;()\par             .LifeStyle.Transient);\par         container.Register(\cf2 Component\cf0 \par             .For&amp;lt;\cf2 IBar\cf0 &amp;gt;()\par             .ImplementedBy&amp;lt;\cf2 Bar\cf0 &amp;gt;());\par \par         \cf1 return\cf0  container.Kernel;\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;FooServiceHostFactory&lt;/span&gt; : &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DefaultServiceHostFactory&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; FooServiceHostFactory()&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;base&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;FooServiceHostFactory&lt;/span&gt;.CreateKernel())&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;/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;IKernel&lt;/span&gt; CreateKernel()&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; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddFacility&amp;lt;&lt;span style="color: #2b91af"&gt;WcfFacility&lt;/span&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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&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; .For&amp;lt;&lt;span style="color: #2b91af"&gt;FooService&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; .LifeStyle.Transient);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&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; .For&amp;lt;&lt;span style="color: #2b91af"&gt;IBar&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; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;Bar&lt;/span&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;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; container.Kernel;&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;
Although it feels a little odd to create a container and then not really use it, but
only its Kernel property, this works like a charm. It correctly wires up this FooService:
&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 FooService\cf0  : \cf2 IFooService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IBar\cf0  bar;\par \par     \cf1 public\cf0  FooService(\cf2 IBar\cf0  bar)\par     \{\par         \cf1 if\cf0  (bar == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "bar"\cf0 );\par         \}\par \par         \cf1 this\cf0 .bar = bar;\par     \}\par \par \cf1     #region\cf0  IFooService Members\par \par     \cf1 public\cf0  \cf1 string\cf0  Foo()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .bar.Baz;\par     \}\par \par \cf1     #endregion\cf0 \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;FooService&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IFooService&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;IBar&lt;/span&gt; bar;&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; FooService(&lt;span style="color: #2b91af"&gt;IBar&lt;/span&gt; bar)&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; (bar
== &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;"bar"&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;.bar
= bar;&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; IFooService 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;string&lt;/span&gt; Foo()&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: blue"&gt;this&lt;/span&gt;.bar.Baz;&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;
However, instead of the static CreateKernel method that creates the IKernel instance, &lt;a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/5401a7189f8295af/2dabe6cbb3c63488?q="&gt;I
suggest that the WCF Facility utilizes the Factory Method pattern&lt;/a&gt;. As the WCF
Facility has not yet been released, perhaps there’s still time for that change.
&lt;/p&gt;
&lt;p&gt;
In any case, the WCF Facility saves you from writing a lot of infrastructure code
if you would like to wire your WCF services with Castle Windsor.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f1a71969-0584-4a15-9395-9f2ac65f104b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
      <category>Services</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=b0aa9448-ae3b-4b35-a897-54069e8a5c5f</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=b0aa9448-ae3b-4b35-a897-54069e8a5c5f</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For a while I’ve been wondering about the lifetime behavior of custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory.aspx">ServiceHostFactory</a> classes
hosted in IIS. Does IIS create an instance per request? Or a single instance to handle
all requests?
</p>
        <p>
I decided to find out, so I wrote a little test service. The conclusion seems to be
that there is only a single instance that servers as a factory for all requests. This
is very fortunate, since it gives us an excellent place to host a DI Container. The
container can then manage the lifetime of all components, including Singletons that
will live for the duration of the process.
</p>
        <p>
If you are curious how I arrived at this conclusion, here’s the code I wrote. I started
out with this custom ServiceHostFactory:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 PocServiceHostFactory\cf0  : \cf2 ServiceHostFactory\cf0 \par \{\par     \cf1 private\cf0  \cf1 static\cf0  \cf1 int\cf0  number = 1;\par \par     \cf1 public\cf0  PocServiceHostFactory()\par     \{\par         \cf2 Interlocked\cf0 .Increment(\par             \cf1 ref\cf0  \cf2 PocServiceHostFactory\cf0 .number);\par     \}\par \par     \cf1 protected\cf0  \cf1 override\cf0  \cf2 ServiceHost\cf0  CreateServiceHost(\par         \cf2 Type\cf0  serviceType, \cf2 Uri\cf0 [] baseAddresses)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 PocServiceHost\cf0 (\par             \cf2 PocServiceHostFactory\cf0 .number, serviceType,\par             baseAddresses);\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">PocServiceHostFactory</span> : <span style="color: #2b91af">ServiceHostFactory</span></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: blue">int</span> number
= 1;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> PocServiceHostFactory()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Interlocked</span>.Increment(</pre>
          <pre style="margin: 0px">            <span style="color: blue">ref</span><span style="color: #2b91af">PocServiceHostFactory</span>.number);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: #2b91af">ServiceHost</span> CreateServiceHost(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Type</span> serviceType, <span style="color: #2b91af">Uri</span>[]
baseAddresses)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">PocServiceHost</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #2b91af">PocServiceHostFactory</span>.number,
serviceType,</pre>
          <pre style="margin: 0px">            baseAddresses);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The idea is that every time a new instance of ServiceHostFactory is created, the static
number is incremented.
</p>
        <p>
The PocServiceHostFactory just forwards the number to the PocServiceHost:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 PocServiceHost\cf0  : \cf2 ServiceHost\cf0 \par \{\par     \cf1 public\cf0  PocServiceHost(\cf1 int\cf0  number, \cf2 Type\cf0  serviceType,\par         \cf2 Uri\cf0 [] baseAddresses)\par         : \cf1 base\cf0 (serviceType, baseAddresses)\par     \{\par         \cf1 foreach\cf0  (\cf1 var\cf0  cd \cf1 in\cf0  \par             \cf1 this\cf0 .ImplementedContracts.Values)\par         \{\par             cd.Behaviors.Add(\par                 \cf1 new\cf0  \cf2 NumberServiceInstanceProvider\cf0 (\par                     number));\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">PocServiceHost</span> : <span style="color: #2b91af">ServiceHost</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> PocServiceHost(<span style="color: blue">int</span> number, <span style="color: #2b91af">Type</span> serviceType,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Uri</span>[]
baseAddresses)</pre>
          <pre style="margin: 0px">        : <span style="color: blue">base</span>(serviceType,
baseAddresses)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">foreach</span> (<span style="color: blue">var</span> cd <span style="color: blue">in</span></pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.ImplementedContracts.Values)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            cd.Behaviors.Add(</pre>
          <pre style="margin: 0px">                <span style="color: blue">new</span><span style="color: #2b91af">NumberServiceInstanceProvider</span>(</pre>
          <pre style="margin: 0px">                    number));</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The PocServiceHost just forwards the number to the NumberServiceInstanceProvider:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 NumberServiceInstanceProvider\cf0  : \par     \cf2 IInstanceProvider\cf0 , \cf2 IContractBehavior\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberServiceInstanceProvider(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  IInstanceProvider Members\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf2 Message\cf0  message)\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .GetInstance(instanceContext);\par     \}\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 NumberService\cf0 (\cf1 this\cf0 .number);\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ReleaseInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf1 object\cf0  instance)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \par \par \cf1     #region\cf0  IContractBehavior Members\par \par     \cf1 public\cf0  \cf1 void\cf0  AddBindingParameters(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 BindingParameterCollection\cf0  bindingParameters)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyClientBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 ClientRuntime\cf0  clientRuntime)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyDispatchBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 DispatchRuntime\cf0  dispatchRuntime)\par     \{\par         dispatchRuntime.InstanceProvider = \cf1 this\cf0 ;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Validate(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \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">NumberServiceInstanceProvider</span> : </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IInstanceProvider</span>, <span style="color: #2b91af">IContractBehavior</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> number;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> NumberServiceInstanceProvider(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.number
= number;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IInstanceProvider Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">object</span> GetInstance(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">InstanceContext</span> instanceContext,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Message</span> message)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.GetInstance(instanceContext);</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">object</span> GetInstance(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">InstanceContext</span> instanceContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">NumberService</span>(<span style="color: blue">this</span>.number);</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> ReleaseInstance(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">InstanceContext</span> instanceContext,</pre>
          <pre style="margin: 0px">        <span style="color: blue">object</span> instance)</pre>
          <pre style="margin: 0px">    {</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>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IContractBehavior Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> AddBindingParameters(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">BindingParameterCollection</span> bindingParameters)</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> ApplyClientBehavior(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ClientRuntime</span> clientRuntime)</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> ApplyDispatchBehavior(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">DispatchRuntime</span> dispatchRuntime)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        dispatchRuntime.InstanceProvider = <span style="color: blue">this</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">void</span> Validate(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint)</pre>
          <pre style="margin: 0px">    {</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 relevant part of NumberServiceInstanceProvider is the GetInstanceMethod that simply
forwards the number to the NumberService:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 NumberService\cf0  : \cf2 INumberService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberService(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  INumberService Members\par \par     \cf1 public\cf0  \cf1 int\cf0  GetNumber()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .number;\par     \}\par \par \cf1     #endregion\cf0 \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">NumberService</span> : <span style="color: #2b91af">INumberService</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> number;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> NumberService(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.number
= number;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> INumberService Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">int</span> GetNumber()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.number;</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>
As you can see, NumberService simply returns the injected number.
</p>
        <p>
The experiment is now to host NumberService in IIS using PocServiceHostFactory. If
there is only one ServiceHostFactory per application process, we would expect that
the same number (2) is returned every time we invoke the GetNumber operation. If,
on the other hand, a new instance of ServiceHostFactory is created per request, we
would expect the number to increase for every request.
</p>
        <p>
To test this I spun up a few instances of WcfTestClient.exe and invoked the operation.
It consistently returns <em>2</em> across multiple clients and multiple requests.
This supports the hypothesis that there is only one ServiceHostFactory per service
process.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b0aa9448-ae3b-4b35-a897-54069e8a5c5f" />
      </body>
      <title>ServiceHostFactory lifetime</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</guid>
      <link>http://blog.ploeh.dk/2010/05/17/ServiceHostFactoryLifetime.aspx</link>
      <pubDate>Mon, 17 May 2010 05:42:33 GMT</pubDate>
      <description>&lt;p&gt;
For a while I’ve been wondering about the lifetime behavior of custom &lt;a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory.aspx"&gt;ServiceHostFactory&lt;/a&gt; classes
hosted in IIS. Does IIS create an instance per request? Or a single instance to handle
all requests?
&lt;/p&gt;
&lt;p&gt;
I decided to find out, so I wrote a little test service. The conclusion seems to be
that there is only a single instance that servers as a factory for all requests. This
is very fortunate, since it gives us an excellent place to host a DI Container. The
container can then manage the lifetime of all components, including Singletons that
will live for the duration of the process.
&lt;/p&gt;
&lt;p&gt;
If you are curious how I arrived at this conclusion, here’s the code I wrote. I started
out with this custom ServiceHostFactory:
&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 PocServiceHostFactory\cf0  : \cf2 ServiceHostFactory\cf0 \par \{\par     \cf1 private\cf0  \cf1 static\cf0  \cf1 int\cf0  number = 1;\par \par     \cf1 public\cf0  PocServiceHostFactory()\par     \{\par         \cf2 Interlocked\cf0 .Increment(\par             \cf1 ref\cf0  \cf2 PocServiceHostFactory\cf0 .number);\par     \}\par \par     \cf1 protected\cf0  \cf1 override\cf0  \cf2 ServiceHost\cf0  CreateServiceHost(\par         \cf2 Type\cf0  serviceType, \cf2 Uri\cf0 [] baseAddresses)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 PocServiceHost\cf0 (\par             \cf2 PocServiceHostFactory\cf0 .number, serviceType,\par             baseAddresses);\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;PocServiceHostFactory&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;ServiceHostFactory&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;static&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; number
= 1;&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; PocServiceHostFactory()&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;Interlocked&lt;/span&gt;.Increment(&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;ref&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PocServiceHostFactory&lt;/span&gt;.number);&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;protected&lt;/span&gt; &lt;span style="color: blue"&gt;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ServiceHost&lt;/span&gt; CreateServiceHost(&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;Type&lt;/span&gt; serviceType, &lt;span style="color: #2b91af"&gt;Uri&lt;/span&gt;[]
baseAddresses)&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: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PocServiceHost&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: #2b91af"&gt;PocServiceHostFactory&lt;/span&gt;.number,
serviceType,&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; baseAddresses);&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 idea is that every time a new instance of ServiceHostFactory is created, the static
number is incremented.
&lt;/p&gt;
&lt;p&gt;
The PocServiceHostFactory just forwards the number to the PocServiceHost:
&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 PocServiceHost\cf0  : \cf2 ServiceHost\cf0 \par \{\par     \cf1 public\cf0  PocServiceHost(\cf1 int\cf0  number, \cf2 Type\cf0  serviceType,\par         \cf2 Uri\cf0 [] baseAddresses)\par         : \cf1 base\cf0 (serviceType, baseAddresses)\par     \{\par         \cf1 foreach\cf0  (\cf1 var\cf0  cd \cf1 in\cf0  \par             \cf1 this\cf0 .ImplementedContracts.Values)\par         \{\par             cd.Behaviors.Add(\par                 \cf1 new\cf0  \cf2 NumberServiceInstanceProvider\cf0 (\par                     number));\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;PocServiceHost&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;ServiceHost&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; PocServiceHost(&lt;span style="color: blue"&gt;int&lt;/span&gt; number, &lt;span style="color: #2b91af"&gt;Type&lt;/span&gt; serviceType,&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;Uri&lt;/span&gt;[]
baseAddresses)&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;base&lt;/span&gt;(serviceType,
baseAddresses)&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;foreach&lt;/span&gt; (&lt;span style="color: blue"&gt;var&lt;/span&gt; cd &lt;span style="color: blue"&gt;in&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;this&lt;/span&gt;.ImplementedContracts.Values)&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; cd.Behaviors.Add(&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;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NumberServiceInstanceProvider&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; number));&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 PocServiceHost just forwards the number to the NumberServiceInstanceProvider:
&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 NumberServiceInstanceProvider\cf0  : \par     \cf2 IInstanceProvider\cf0 , \cf2 IContractBehavior\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberServiceInstanceProvider(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  IInstanceProvider Members\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf2 Message\cf0  message)\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .GetInstance(instanceContext);\par     \}\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 NumberService\cf0 (\cf1 this\cf0 .number);\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ReleaseInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf1 object\cf0  instance)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \par \par \cf1     #region\cf0  IContractBehavior Members\par \par     \cf1 public\cf0  \cf1 void\cf0  AddBindingParameters(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 BindingParameterCollection\cf0  bindingParameters)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyClientBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 ClientRuntime\cf0  clientRuntime)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyDispatchBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 DispatchRuntime\cf0  dispatchRuntime)\par     \{\par         dispatchRuntime.InstanceProvider = \cf1 this\cf0 ;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Validate(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \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;NumberServiceInstanceProvider&lt;/span&gt; : &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IInstanceProvider&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IContractBehavior&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; number;&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; NumberServiceInstanceProvider(&lt;span style="color: blue"&gt;int&lt;/span&gt; number)&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;.number
= number;&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; IInstanceProvider 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;object&lt;/span&gt; GetInstance(&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;InstanceContext&lt;/span&gt; instanceContext,&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;Message&lt;/span&gt; message)&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: blue"&gt;this&lt;/span&gt;.GetInstance(instanceContext);&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;object&lt;/span&gt; GetInstance(&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;InstanceContext&lt;/span&gt; instanceContext)&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: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NumberService&lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.number);&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; ReleaseInstance(&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;InstanceContext&lt;/span&gt; instanceContext,&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; instance)&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;/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;&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; IContractBehavior 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; AddBindingParameters(&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;ContractDescription&lt;/span&gt; contractDescription,&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;ServiceEndpoint&lt;/span&gt; endpoint,&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;BindingParameterCollection&lt;/span&gt; bindingParameters)&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;/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; ApplyClientBehavior(&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;ContractDescription&lt;/span&gt; contractDescription,&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;ServiceEndpoint&lt;/span&gt; endpoint,&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;ClientRuntime&lt;/span&gt; clientRuntime)&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;/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; ApplyDispatchBehavior(&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;ContractDescription&lt;/span&gt; contractDescription,&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;ServiceEndpoint&lt;/span&gt; endpoint,&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;DispatchRuntime&lt;/span&gt; dispatchRuntime)&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; dispatchRuntime.InstanceProvider = &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; }&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; Validate(&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;ContractDescription&lt;/span&gt; contractDescription,&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;ServiceEndpoint&lt;/span&gt; endpoint)&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;/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 relevant part of NumberServiceInstanceProvider is the GetInstanceMethod that simply
forwards the number to the NumberService:
&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 NumberService\cf0  : \cf2 INumberService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberService(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  INumberService Members\par \par     \cf1 public\cf0  \cf1 int\cf0  GetNumber()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .number;\par     \}\par \par \cf1     #endregion\cf0 \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;NumberService&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;INumberService&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; number;&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; NumberService(&lt;span style="color: blue"&gt;int&lt;/span&gt; number)&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;.number
= number;&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; INumberService 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;int&lt;/span&gt; GetNumber()&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: blue"&gt;this&lt;/span&gt;.number;&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;
As you can see, NumberService simply returns the injected number.
&lt;/p&gt;
&lt;p&gt;
The experiment is now to host NumberService in IIS using PocServiceHostFactory. If
there is only one ServiceHostFactory per application process, we would expect that
the same number (2) is returned every time we invoke the GetNumber operation. If,
on the other hand, a new instance of ServiceHostFactory is created per request, we
would expect the number to increase for every request.
&lt;/p&gt;
&lt;p&gt;
To test this I spun up a few instances of WcfTestClient.exe and invoked the operation.
It consistently returns &lt;em&gt;2&lt;/em&gt; across multiple clients and multiple requests.
This supports the hypothesis that there is only one ServiceHostFactory per service
process.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b0aa9448-ae3b-4b35-a897-54069e8a5c5f" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</comments>
      <category>Dependency Injection</category>
      <category>Services</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=589220df-9778-41a9-a7df-e0543901bb2b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=589220df-9778-41a9-a7df-e0543901bb2b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.manning.com/seemann/">My book</a> contains a section on the <a href="http://blogs.msdn.com/ploeh/archive/2007/07/23/AmbientContext.aspx">Ambient
Context</a> pattern that uses a TimeProvider as an example. It’s used 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 this\cf0 .closedAt = \cf4 TimeProvider\cf0 .Current.UtcNow;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">this</span>.closedAt
= <span style="color: #2b91af">TimeProvider</span>.Current.UtcNow;</pre>
        </div>
        <p>
Yesterday I was TDDing a state machine that consumes TimeProvider and needed to freeze
and advance time at different places in the test. Always on the lookout for making
unit tests more readable, I decided to have a little fun with literal extensions and
TimeProvider. I ended up with this test:
</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;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  fixture = \cf3 new\cf0  \cf5 WcfFixture\cf0 ();\par ??\par ??\cf5 DateTime\cf0 .Now.Freeze();\par ??\par ??fixture.Register(1.Minutes());\par ??\cf3 var\cf0  sut = fixture.CreateAnonymous&lt;\cf5 CircuitBreaker\cf0 &gt;();\par ??sut.PutInOpenState();\par ??\par ??2.Minutes().Pass();\par ??\cf1 // Exercise system\par ??\cf0 sut.Guard();\par ??\cf1 // Verify outcome\par ??\cf5 Assert\cf0 .IsInstanceOfType(sut.State,\par ??    \cf3 typeof\cf0 (\cf5 HalfOpenCircuitState\cf0 ));\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> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">WcfFixture</span>();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">DateTime</span>.Now.Freeze();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">fixture.Register(1.Minutes());</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">CircuitBreaker</span>&gt;();</pre>
          <pre style="margin: 0px">sut.PutInOpenState();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">2.Minutes().Pass();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Exercise system</span>
          </pre>
          <pre style="margin: 0px">sut.Guard();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Verify outcome</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">Assert</span>.IsInstanceOfType(sut.State,</pre>
          <pre style="margin: 0px">    <span style="color: blue">typeof</span>(<span style="color: #2b91af">HalfOpenCircuitState</span>));</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Teardown</span>
          </pre>
        </div>
        <p>
There are several items of note. Imagine that we can freeze time!
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 DateTime\cf0 .Now.Freeze();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">DateTime</span>.Now.Freeze();</pre>
        </div>
        <p>
With the TimeProvider and an extension method, we can:
</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 static\cf0  \cf1 void\cf0  Freeze(\cf1 this\cf0  \cf4 DateTime\cf0  dt)\par ??\{\par ??    \cf1 var\cf0  timeProviderStub = \cf1 new\cf0  \cf4 Mock\cf0 &lt;\cf4 TimeProvider\cf0 &gt;();\par ??    timeProviderStub.SetupGet(tp =&gt; tp.UtcNow).Returns(dt);\par ??    \cf4 TimeProvider\cf0 .Current = timeProviderStub.Object;\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">static</span>
            <span style="color: blue">void</span> Freeze(<span style="color: blue">this</span><span style="color: #2b91af">DateTime</span> dt)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> timeProviderStub
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">TimeProvider</span>&gt;();</pre>
          <pre style="margin: 0px">    timeProviderStub.SetupGet(tp =&gt; tp.UtcNow).Returns(dt);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">TimeProvider</span>.Current
= timeProviderStub.Object;</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This effectively sets up the TimeProvider to always return the same time.
</p>
        <p>
Later in the test I state that 2 minutes pass:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;}??\fs20 2.Minutes().Pass();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">2.Minutes().Pass();</pre>
        </div>
        <p>
I particularly like the grammatically correct English. This is accomplished with a
combination of a literal extension and changing the state of TimeProvider.
</p>
        <p>
First, the literal extension:
</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 static\cf0  \cf4 TimeSpan\cf0  Minutes(\cf1 this\cf0  \cf1 int\cf0  m)\par ??\{\par ??    \cf1 return\cf0  \cf4 TimeSpan\cf0 .FromMinutes(m);\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">static</span>
            <span style="color: #2b91af">TimeSpan</span> Minutes(<span style="color: blue">this</span><span style="color: blue">int</span> m)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span><span style="color: #2b91af">TimeSpan</span>.FromMinutes(m);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Given the TimeSpan returned from the Minutes method, I can now invoke the Pass extension
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 internal\cf0  \cf1 static\cf0  \cf1 void\cf0  Pass(\cf1 this\cf0  \cf4 TimeSpan\cf0  ts)\par ??\{\par ??    \cf1 var\cf0  previousTime = \cf4 TimeProvider\cf0 .Current.UtcNow;\par ??    (previousTime + ts).Freeze();\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">static</span>
            <span style="color: blue">void</span> Pass(<span style="color: blue">this</span><span style="color: #2b91af">TimeSpan</span> ts)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> previousTime
= <span style="color: #2b91af">TimeProvider</span>.Current.UtcNow;</pre>
          <pre style="margin: 0px">    (previousTime + ts).Freeze();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Note that I just add the TimeSpan to the current time and invoke the Freeze extension
method with the new value.
</p>
        <p>
Last, but not least, I should point out that the PutInOpenState method isn’t some
smelly test-specific method on the <a href="http://xunitpatterns.com/SUT.html">SUT</a>,
but rather yet another extension method.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=589220df-9778-41a9-a7df-e0543901bb2b" />
      </body>
      <title>Fun with literal extensions and Ambient Context</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/27/FunWithLiteralExtensionsAndAmbientContext.aspx</link>
      <pubDate>Tue, 27 Apr 2010 04:24:25 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://www.manning.com/seemann/"&gt;My book&lt;/a&gt; contains a section on the &lt;a href="http://blogs.msdn.com/ploeh/archive/2007/07/23/AmbientContext.aspx"&gt;Ambient
Context&lt;/a&gt; pattern that uses a TimeProvider as an example. It’s used 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 this\cf0 .closedAt = \cf4 TimeProvider\cf0 .Current.UtcNow;}
--&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;this&lt;/span&gt;.closedAt
= &lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;.Current.UtcNow;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Yesterday I was TDDing a state machine that consumes TimeProvider and needed to freeze
and advance time at different places in the test. Always on the lookout for making
unit tests more readable, I decided to have a little fun with literal extensions and
TimeProvider. I ended up with this test:
&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;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  fixture = \cf3 new\cf0  \cf5 WcfFixture\cf0 ();\par ??\par ??\cf5 DateTime\cf0 .Now.Freeze();\par ??\par ??fixture.Register(1.Minutes());\par ??\cf3 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf5 CircuitBreaker\cf0 &amp;gt;();\par ??sut.PutInOpenState();\par ??\par ??2.Minutes().Pass();\par ??\cf1 // Exercise system\par ??\cf0 sut.Guard();\par ??\cf1 // Verify outcome\par ??\cf5 Assert\cf0 .IsInstanceOfType(sut.State,\par ??    \cf3 typeof\cf0 (\cf5 HalfOpenCircuitState\cf0 ));\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; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WcfFixture&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: #2b91af"&gt;DateTime&lt;/span&gt;.Now.Freeze();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.Register(1.Minutes());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;CircuitBreaker&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.PutInOpenState();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;2.Minutes().Pass();&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.Guard();&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;&lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsInstanceOfType(sut.State,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HalfOpenCircuitState&lt;/span&gt;));&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;
There are several items of note. Imagine that we can freeze time!
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 DateTime\cf0 .Now.Freeze();}
--&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;DateTime&lt;/span&gt;.Now.Freeze();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With the TimeProvider and an extension method, we can:
&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 static\cf0  \cf1 void\cf0  Freeze(\cf1 this\cf0  \cf4 DateTime\cf0  dt)\par ??\{\par ??    \cf1 var\cf0  timeProviderStub = \cf1 new\cf0  \cf4 Mock\cf0 &amp;lt;\cf4 TimeProvider\cf0 &amp;gt;();\par ??    timeProviderStub.SetupGet(tp =&amp;gt; tp.UtcNow).Returns(dt);\par ??    \cf4 TimeProvider\cf0 .Current = timeProviderStub.Object;\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;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Freeze(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt; dt)&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; timeProviderStub
= &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;TimeProvider&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeProviderStub.SetupGet(tp =&amp;gt; tp.UtcNow).Returns(dt);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;.Current
= timeProviderStub.Object;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This effectively sets up the TimeProvider to always return the same time.
&lt;/p&gt;
&lt;p&gt;
Later in the test I state that 2 minutes pass:
&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;}??\fs20 2.Minutes().Pass();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;2.Minutes().Pass();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I particularly like the grammatically correct English. This is accomplished with a
combination of a literal extension and changing the state of TimeProvider.
&lt;/p&gt;
&lt;p&gt;
First, the literal extension:
&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 static\cf0  \cf4 TimeSpan\cf0  Minutes(\cf1 this\cf0  \cf1 int\cf0  m)\par ??\{\par ??    \cf1 return\cf0  \cf4 TimeSpan\cf0 .FromMinutes(m);\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;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt; Minutes(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; m)&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; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;.FromMinutes(m);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Given the TimeSpan returned from the Minutes method, I can now invoke the Pass extension
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 internal\cf0  \cf1 static\cf0  \cf1 void\cf0  Pass(\cf1 this\cf0  \cf4 TimeSpan\cf0  ts)\par ??\{\par ??    \cf1 var\cf0  previousTime = \cf4 TimeProvider\cf0 .Current.UtcNow;\par ??    (previousTime + ts).Freeze();\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;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Pass(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt; ts)&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; previousTime
= &lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;.Current.UtcNow;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; (previousTime + ts).Freeze();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Note that I just add the TimeSpan to the current time and invoke the Freeze extension
method with the new value.
&lt;/p&gt;
&lt;p&gt;
Last, but not least, I should point out that the PutInOpenState method isn’t some
smelly test-specific method on the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;,
but rather yet another extension method.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=589220df-9778-41a9-a7df-e0543901bb2b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</comments>
      <category>Dependency Injection</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=ce797146-6cc9-4322-b40d-990395d69e36</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ce797146-6cc9-4322-b40d-990395d69e36</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I recently had the need to change the lifestyles of all components in a WindsorContainer
(read on to the end if you want to know why). This turned out to be amazingly simple
to do.
</p>
        <p>
The problem was this: I had numerous components registered in a WindsorContainer,
some of them as Singletons, some as Transients and yet again some as PerWebRequest.
Configuration was even defined in numerous IWindsorInstallers, including some distributed
XML files. I now needed to spin up a second container with the same configuration
as the first one, <em>except</em> that the lifestyles should be all Singletons across
the board.
</p>
        <p>
This can be easily accomplished by implementing a custom IContributeComponentModelConstruction
type. Here’s a simple example:
</p>
        <p>
Consider this IWindsorInstaller:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooInstaller\cf0  : \cf2 IWindsorInstaller\cf0 \par \{\par \cf1     #region\cf0  IWindsorInstaller Members\par \par     \cf1 public\cf0  \cf1 void\cf0  Install(\cf2 IWindsorContainer\cf0  container,\par         \cf2 IConfigurationStore\cf0  store)\par     \{\par         container.Register(\cf2 Component\cf0 \par             .For&lt;\cf2 IFoo\cf0 &gt;()\par             .ImplementedBy&lt;\cf2 Foo\cf0 &gt;()\par             .LifeStyle.Transient);\par     \}\par \par \cf1     #endregion\cf0 \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">FooInstaller</span> : <span style="color: #2b91af">IWindsorInstaller</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IWindsorInstaller Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Install(<span style="color: #2b91af">IWindsorContainer</span> container,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">IConfigurationStore</span> store)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">            .For&lt;<span style="color: #2b91af">IFoo</span>&gt;()</pre>
          <pre style="margin: 0px">            .ImplementedBy&lt;<span style="color: #2b91af">Foo</span>&gt;()</pre>
          <pre style="margin: 0px">            .LifeStyle.Transient);</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 important point to notice is that it registers the lifestyle as Transient. In
other words, this container will always return new Foo instances:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();</pre>
          <pre style="margin: 0px">container.Install(<span style="color: blue">new</span><span style="color: #2b91af">FooInstaller</span>());</pre>
        </div>
        <p>
We can override this behavior by adding this custom IContributeComponentModelConstruction:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 SingletonEqualizer\cf0  :\par     \cf2 IContributeComponentModelConstruction\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  ProcessModel(\cf2 IKernel\cf0  kernel, \par         \cf2 ComponentModel\cf0  model)\par     \{\par         model.LifestyleType = \cf2 LifestyleType\cf0 .Singleton;\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">SingletonEqualizer</span> :</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IContributeComponentModelConstruction</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> ProcessModel(<span style="color: #2b91af">IKernel</span> kernel, </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ComponentModel</span> model)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        model.LifestyleType = <span style="color: #2b91af">LifestyleType</span>.Singleton;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this very simple example, I always set the lifestyle type to the same value, but
obviously we can write as complex code in the ProcessModel method as we would like.
We can now configure the container like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Kernel.ComponentModelBuilder\par     .AddContributor(\cf1 new\cf0  \cf2 SingletonEqualizer\cf0 ());\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();</pre>
          <pre style="margin: 0px">container.Kernel.ComponentModelBuilder</pre>
          <pre style="margin: 0px">    .AddContributor(<span style="color: blue">new</span><span style="color: #2b91af">SingletonEqualizer</span>());</pre>
          <pre style="margin: 0px">container.Install(<span style="color: blue">new</span><span style="color: #2b91af">FooInstaller</span>());</pre>
        </div>
        <p>
With this configuration we will now get the same instance of Foo every time we Resolve
IFoo.
</p>
        <p>
We did I need this? Because my application is a web application and I’m using the
PerWebRequest lifestyle in a number of places. However, I needed to spin up a second
container that would compose object hierarchies for a background process. This background
process needs the same component configuration as the rest of the application, but
can’t use the PerWebRequest lifestyle as there will be no web request available to
the background process. Hence the need to change lifestyles across the board.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ce797146-6cc9-4322-b40d-990395d69e36" />
      </body>
      <title>Changing Windsor lifestyles after the fact</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/26/ChangingWindsorLifestylesAfterTheFact.aspx</link>
      <pubDate>Mon, 26 Apr 2010 05:09:42 GMT</pubDate>
      <description>&lt;p&gt;
I recently had the need to change the lifestyles of all components in a WindsorContainer
(read on to the end if you want to know why). This turned out to be amazingly simple
to do.
&lt;/p&gt;
&lt;p&gt;
The problem was this: I had numerous components registered in a WindsorContainer,
some of them as Singletons, some as Transients and yet again some as PerWebRequest.
Configuration was even defined in numerous IWindsorInstallers, including some distributed
XML files. I now needed to spin up a second container with the same configuration
as the first one, &lt;em&gt;except&lt;/em&gt; that the lifestyles should be all Singletons across
the board.
&lt;/p&gt;
&lt;p&gt;
This can be easily accomplished by implementing a custom IContributeComponentModelConstruction
type. Here’s a simple example:
&lt;/p&gt;
&lt;p&gt;
Consider this IWindsorInstaller:
&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 FooInstaller\cf0  : \cf2 IWindsorInstaller\cf0 \par \{\par \cf1     #region\cf0  IWindsorInstaller Members\par \par     \cf1 public\cf0  \cf1 void\cf0  Install(\cf2 IWindsorContainer\cf0  container,\par         \cf2 IConfigurationStore\cf0  store)\par     \{\par         container.Register(\cf2 Component\cf0 \par             .For&amp;lt;\cf2 IFoo\cf0 &amp;gt;()\par             .ImplementedBy&amp;lt;\cf2 Foo\cf0 &amp;gt;()\par             .LifeStyle.Transient);\par     \}\par \par \cf1     #endregion\cf0 \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;FooInstaller&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IWindsorInstaller&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&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; IWindsorInstaller 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; Install(&lt;span style="color: #2b91af"&gt;IWindsorContainer&lt;/span&gt; container,&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;IConfigurationStore&lt;/span&gt; store)&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; container.Register(&lt;span style="color: #2b91af"&gt;Component&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; .For&amp;lt;&lt;span style="color: #2b91af"&gt;IFoo&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; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;Foo&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; .LifeStyle.Transient);&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 important point to notice is that it registers the lifestyle as Transient. In
other words, this container will always return new Foo instances:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\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; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Install(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooInstaller&lt;/span&gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We can override this behavior by adding this custom IContributeComponentModelConstruction:
&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 SingletonEqualizer\cf0  :\par     \cf2 IContributeComponentModelConstruction\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  ProcessModel(\cf2 IKernel\cf0  kernel, \par         \cf2 ComponentModel\cf0  model)\par     \{\par         model.LifestyleType = \cf2 LifestyleType\cf0 .Singleton;\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;SingletonEqualizer&lt;/span&gt; :&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IContributeComponentModelConstruction&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; ProcessModel(&lt;span style="color: #2b91af"&gt;IKernel&lt;/span&gt; kernel, &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;ComponentModel&lt;/span&gt; model)&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; model.LifestyleType = &lt;span style="color: #2b91af"&gt;LifestyleType&lt;/span&gt;.Singleton;&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 this very simple example, I always set the lifestyle type to the same value, but
obviously we can write as complex code in the ProcessModel method as we would like.
We can now configure the container like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Kernel.ComponentModelBuilder\par     .AddContributor(\cf1 new\cf0  \cf2 SingletonEqualizer\cf0 ());\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\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; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Kernel.ComponentModelBuilder&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .AddContributor(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SingletonEqualizer&lt;/span&gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Install(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooInstaller&lt;/span&gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With this configuration we will now get the same instance of Foo every time we Resolve
IFoo.
&lt;/p&gt;
&lt;p&gt;
We did I need this? Because my application is a web application and I’m using the
PerWebRequest lifestyle in a number of places. However, I needed to spin up a second
container that would compose object hierarchies for a background process. This background
process needs the same component configuration as the rest of the application, but
can’t use the PerWebRequest lifestyle as there will be no web request available to
the background process. Hence the need to change lifestyles across the board.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ce797146-6cc9-4322-b40d-990395d69e36" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=6cdc7e45-ad80-4766-ba8f-cc4d82752572</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,6cdc7e45-ad80-4766-ba8f-cc4d82752572.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,6cdc7e45-ad80-4766-ba8f-cc4d82752572.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=6cdc7e45-ad80-4766-ba8f-cc4d82752572</wfw:commentRss>
      <slash:comments>7</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
About a month ago I decided to migrate from MSTest to <a href="http://xunit.codeplex.com/wikipage">xUnit.net</a>,
and while I am still in the process, I haven’t regretted it yet, and I don’t expect
to. <a href="http://autofixture.codeplex.com/">AutoFixture</a> has already moved over,
and I’m slowly migrating all the sample code for <a href="http://www.manning.com/seemann/">my
book</a>.
</p>
        <p>
Recently I was asked <em>why</em>, which prompted me to write this post.
</p>
        <p>
I’m not moving away from MSTest for one single reason. It’s rather like lots of small
reasons.
</p>
        <p>
When I originally started out with TDD, I used nUnit – it was more or less the only
unit testing framework available for .NET at the time. When MSTest came, the change
was natural, since I worked for Microsoft at the time. This is not the case anymore,
but it still took me most of a year to finally abandon MSTest.
</p>
        <p>
There was one thing that really made me cling to MSTest, and that was the IDE integration,
but over time, I started to realize that this was the <em>only</em> reason, and even
that was getting flaky.
</p>
        <p>
When I started to think about all the things that left me dissatisfied, making the
decision was easy:
</p>
        <ul>
          <li>
First of all, MSTest isn’t extensible, but xUnit.net is. In xUnit.net, I can extend
the Fact or Theory attributes (and I intent to), while in MSTest, I will have to play
with the cards I’ve been dealt. I think I could live with all the other issues if
I could just have this one, but no. 
</li>
          <li>
MSTest has no support for parameterized test. xUnit.net does (via the Theory attribute). 
</li>
          <li>
MSTest has no Assert.Throws, although I <a href="https://connect.microsoft.com/VisualStudio/feedback/details/381288/assert-throws-for-mstest">requested
this feature a long time ago</a>. Now Visual Studio 2010 is out, but Assert.Throws
is still nowhere in sight. 
</li>
          <li>
MSTest has no x64 support. Tests always run as x86. Usually it’s no big deal, but
sometimes it’s a really big deal. 
</li>
          <li>
In MSTest, to write unit tests, you must create a special <em>Unit Test Project</em>,
and those are only available for C# and VB.net. Good luck trying to write unit tests
in a more exotic .NET language (like F# on Visual Studio 2008). xUnit.net doesn’t
have this problem. 
</li>
          <li>
MSTest uses Test Lists and .vsmdi files to maintain test lists. Why? I don’t care,
I just want to execute my tests, and the .vsmdi files are in the way. This is particularly
bad when you use TFS, but I’m also moving away from TFS, so that wouldn’t have continued
to be that much of an issue. Still: try having more than one .sln file with unit tests
in the same folder, and watch funny things happen because they need to share the same
.vsmdi file. 
</li>
          <li>
I suppose it’s because of the .vsmdi files, but sometimes I get a Test run error if
I delete a test and run the tests immediately after. That’s a false positive, if anyone
cares. 
</li>
          <li>
MSTest gives special treatment to its own AssertionException, which gets nice formatting
in the Test Results window. All other exceptions (like verification exceptions thrown
by Moq or Rhino Mocks are rendered near-intelligible because MSTest thinks it’s very
important to report the fully qualified name of the exception before its message.
Most of the time, you have to open the Test Details window to see the exception message. 
</li>
          <li>
Last, but not least, I often get cryptic exception messages like this one: <em>Column
'id_column, runid_column' is constrained to be unique.  Value '8c84fa94-04c1-424b-9868-57a2d4851a1d,
d7471c5e-522f-43d3-b2c5-8f5cab55af0e' is already present.</em> This appears in a very
annoying modal MessageBox, but clicking OK and retrying usually works, although sometimes
it even takes two or three attempts before I can get past this error.</li>
        </ul>
        <p>
It not one big thing, it’s just a lot of small, but very annoying things. After three
iterations (VS2005, VS2008 and now VS2010) these issue have still to be addressed,
and I got tired of waiting.
</p>
        <p>
So far, I can only say that I have none of these problems with xUnit.net and the IDE
integration provided by <a href="http://www.testdriven.net/">TestDriven.NET</a>. It’s
just a much smoother experience with much less friction.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6cdc7e45-ad80-4766-ba8f-cc4d82752572" />
      </body>
      <title>Why I’m migrating from MSTest to xUnit.net</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,6cdc7e45-ad80-4766-ba8f-cc4d82752572.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/26/WhyImMigratingFromMSTestToXUnitnet.aspx</link>
      <pubDate>Mon, 26 Apr 2010 04:30:49 GMT</pubDate>
      <description>&lt;p&gt;
About a month ago I decided to migrate from MSTest to &lt;a href="http://xunit.codeplex.com/wikipage"&gt;xUnit.net&lt;/a&gt;,
and while I am still in the process, I haven’t regretted it yet, and I don’t expect
to. &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; has already moved over,
and I’m slowly migrating all the sample code for &lt;a href="http://www.manning.com/seemann/"&gt;my
book&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Recently I was asked &lt;em&gt;why&lt;/em&gt;, which prompted me to write this post.
&lt;/p&gt;
&lt;p&gt;
I’m not moving away from MSTest for one single reason. It’s rather like lots of small
reasons.
&lt;/p&gt;
&lt;p&gt;
When I originally started out with TDD, I used nUnit – it was more or less the only
unit testing framework available for .NET at the time. When MSTest came, the change
was natural, since I worked for Microsoft at the time. This is not the case anymore,
but it still took me most of a year to finally abandon MSTest.
&lt;/p&gt;
&lt;p&gt;
There was one thing that really made me cling to MSTest, and that was the IDE integration,
but over time, I started to realize that this was the &lt;em&gt;only&lt;/em&gt; reason, and even
that was getting flaky.
&lt;/p&gt;
&lt;p&gt;
When I started to think about all the things that left me dissatisfied, making the
decision was easy:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
First of all, MSTest isn’t extensible, but xUnit.net is. In xUnit.net, I can extend
the Fact or Theory attributes (and I intent to), while in MSTest, I will have to play
with the cards I’ve been dealt. I think I could live with all the other issues if
I could just have this one, but no. 
&lt;li&gt;
MSTest has no support for parameterized test. xUnit.net does (via the Theory attribute). 
&lt;li&gt;
MSTest has no Assert.Throws, although I &lt;a href="https://connect.microsoft.com/VisualStudio/feedback/details/381288/assert-throws-for-mstest"&gt;requested
this feature a long time ago&lt;/a&gt;. Now Visual Studio 2010 is out, but Assert.Throws
is still nowhere in sight. 
&lt;li&gt;
MSTest has no x64 support. Tests always run as x86. Usually it’s no big deal, but
sometimes it’s a really big deal. 
&lt;li&gt;
In MSTest, to write unit tests, you must create a special &lt;em&gt;Unit Test Project&lt;/em&gt;,
and those are only available for C# and VB.net. Good luck trying to write unit tests
in a more exotic .NET language (like F# on Visual Studio 2008). xUnit.net doesn’t
have this problem. 
&lt;li&gt;
MSTest uses Test Lists and .vsmdi files to maintain test lists. Why? I don’t care,
I just want to execute my tests, and the .vsmdi files are in the way. This is particularly
bad when you use TFS, but I’m also moving away from TFS, so that wouldn’t have continued
to be that much of an issue. Still: try having more than one .sln file with unit tests
in the same folder, and watch funny things happen because they need to share the same
.vsmdi file. 
&lt;li&gt;
I suppose it’s because of the .vsmdi files, but sometimes I get a Test run error if
I delete a test and run the tests immediately after. That’s a false positive, if anyone
cares. 
&lt;li&gt;
MSTest gives special treatment to its own AssertionException, which gets nice formatting
in the Test Results window. All other exceptions (like verification exceptions thrown
by Moq or Rhino Mocks are rendered near-intelligible because MSTest thinks it’s very
important to report the fully qualified name of the exception before its message.
Most of the time, you have to open the Test Details window to see the exception message. 
&lt;li&gt;
Last, but not least, I often get cryptic exception messages like this one: &lt;em&gt;Column
'id_column, runid_column' is constrained to be unique.&amp;nbsp; Value '8c84fa94-04c1-424b-9868-57a2d4851a1d,
d7471c5e-522f-43d3-b2c5-8f5cab55af0e' is already present.&lt;/em&gt; This appears in a very
annoying modal MessageBox, but clicking OK and retrying usually works, although sometimes
it even takes two or three attempts before I can get past this error.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
It not one big thing, it’s just a lot of small, but very annoying things. After three
iterations (VS2005, VS2008 and now VS2010) these issue have still to be addressed,
and I got tired of waiting.
&lt;/p&gt;
&lt;p&gt;
So far, I can only say that I have none of these problems with xUnit.net and the IDE
integration provided by &lt;a href="http://www.testdriven.net/"&gt;TestDriven.NET&lt;/a&gt;. It’s
just a much smoother experience with much less friction.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6cdc7e45-ad80-4766-ba8f-cc4d82752572" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,6cdc7e45-ad80-4766-ba8f-cc4d82752572.aspx</comments>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=f64de247-b9c0-42f1-b927-ebce6dadce97</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,f64de247-b9c0-42f1-b927-ebce6dadce97.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,f64de247-b9c0-42f1-b927-ebce6dadce97.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=f64de247-b9c0-42f1-b927-ebce6dadce97</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> 1.1 is now available on
the CodePlex site! Compared to the Release Candidate, there are no changes.
</p>
        <p>
The <a href="http://autofixture.codeplex.com/releases/view/43351">1.1 release page</a> has
more details about this particular release, but essentially this is the RC promoted
to release status.
</p>
        <p>
Release 1.1 is an interim release that addresses a few issues that appeared since
the release of version 1.0. Work continues on AutoFixture 2.0 in parallel.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f64de247-b9c0-42f1-b927-ebce6dadce97" />
      </body>
      <title>AutoFixture 1.1</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,f64de247-b9c0-42f1-b927-ebce6dadce97.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/10/AutoFixture11.aspx</link>
      <pubDate>Sat, 10 Apr 2010 10:25:23 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 1.1 is now available on
the CodePlex site! Compared to the Release Candidate, there are no changes.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/releases/view/43351"&gt;1.1 release page&lt;/a&gt; has
more details about this particular release, but essentially this is the RC promoted
to release status.
&lt;/p&gt;
&lt;p&gt;
Release 1.1 is an interim release that addresses a few issues that appeared since
the release of version 1.0. Work continues on AutoFixture 2.0 in parallel.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f64de247-b9c0-42f1-b927-ebce6dadce97" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,f64de247-b9c0-42f1-b927-ebce6dadce97.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=002cb292-46c0-4090-83e2-0bdec32b25b4</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,002cb292-46c0-4090-83e2-0bdec32b25b4.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,002cb292-46c0-4090-83e2-0bdec32b25b4.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=002cb292-46c0-4090-83e2-0bdec32b25b4</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
It seems to me that I’ve lately encountered a particular mindset towards Dependency
Injection (DI). People seem to think that it’s only really good for replacing one
data access implementation with another. Once you get to that point, you know that
the following argument isn’t far behind:
</p>
        <blockquote>
          <p>
“That’s all well and good, but we know for certain that we will <em>never</em> exchange
[insert name of RDBMS here] with anything else in this application.”
</p>
        </blockquote>
        <p>
Apart from the hubris of making such a bold statement about the future of any software
endeavor, such a statement reveals the narrow view on DI that its only purpose is
for replacing data access components – and perhaps for unit testing.
</p>
        <p>
Those are relevant reasons for using DI, but they are only <em>some</em> of the reasons.
Let’s briefly revisit why we employ DI.
</p>
        <p>
We use DI to enable loose coupling.
</p>
        <p>
DI is only a means to an end. Even if you <em>never</em> intend to replace your database
and even if you never want to write a single unit test, DI still offers benefits in
form of a more maintainable code base. The loose coupling gives you better separation
of concerns because it allows you to apply the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/Closed
Principle</a>.
</p>
        <p>
Example coming right up:
</p>
        <p>
Imagine that we need to implement a PrécisViewModel class with a TopSellers property
that returns an IEnumerable&lt;string&gt;. To implement this class, we have a data
access component. Let’s use the ubiquitous Repository pattern and define IProductRepository
to see where that leads us:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 interface\cf0  \cf2 IProductRepository\cf0 \par \{\par     \cf2 IEnumerable\cf0 &lt;\cf2 Product\cf0 &gt; SelectTopSellers();\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">IProductRepository</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Product</span>&gt;
SelectTopSellers();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
We can now implement PrécisViewModel like this:
</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 Pr\uinput1\u233 &#233;cisViewModel\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IProductRepository\cf0  repository;\par \par     \cf1 public\cf0  Pr\uinput1\u233 &#233;cisViewModel(\cf2 IProductRepository\cf0  repository)\par     \{\par         \cf1 if\cf0  (repository == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "repository"\cf0 );\par         \}\par \par         \cf1 this\cf0 .repository = repository;\par     \}\par \par     \cf1 public\cf0  \cf2 IEnumerable\cf0 &lt;\cf1 string\cf0 &gt; TopSellers\par     \{\par         \cf1 get\cf0 \par         \{\par             \cf1 var\cf0  topSellers = \par                 \cf1 this\cf0 .repository.SelectTopSellers();\par             \cf1 return\cf0  \cf1 from\cf0  p \cf1 in\cf0  topSellers\par                    \cf1 select\cf0  p.Name;\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">PrécisViewModel</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">IProductRepository</span> repository;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> PrécisViewModel(<span style="color: #2b91af">IProductRepository</span> repository)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (repository
== <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">"repository"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.repository
= repository;</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">IEnumerable</span>&lt;<span style="color: blue">string</span>&gt;
TopSellers</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">get</span></pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> topSellers
= </pre>
          <pre style="margin: 0px">                <span style="color: blue">this</span>.repository.SelectTopSellers();</pre>
          <pre style="margin: 0px">            <span style="color: blue">return</span><span style="color: blue">from</span> p <span style="color: blue">in</span> topSellers</pre>
          <pre style="margin: 0px">                   <span style="color: blue">select</span> p.Name;</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Nothing fancy is going on here. It’s just straight Constructor Injection at work.
</p>
        <p>
Obviously, we can now implement and use a SQL Server-based repository:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  repository = \cf1 new\cf0  \cf2 SqlProductRepository\cf0 ();\par \cf1 var\cf0  vm = \cf1 new\cf0  \cf2 Pr\uinput1\u233 &#233;cisViewModel\cf0 (repository);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> repository
= <span style="color: blue">new</span><span style="color: #2b91af">SqlProductRepository</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> vm
= <span style="color: blue">new</span><span style="color: #2b91af">PrécisViewModel</span>(repository);</pre>
        </div>
        <p>
So what does all this loose coupling buy us? It doesn’t seem to help us a lot.
</p>
        <p>
The real benefit is not yet apparent, but it should become more obvious when we start
adding requirements. Let’s start with some caching. It turns out that the SelectTopSellers
implementation is slow, so we would like to add some caching somewhere.
</p>
        <p>
Where should we add this caching functionality? Without loose coupling, we would more
or less be constrained to adding it to either PrécisViewModel or SqlProductRepository,
but both have issues:
</p>
        <ul>
          <li>
First of all we would be violating the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> (SRP) in both cases. 
</li>
          <li>
If we implement caching in PrécisViewModel, other consumers of the SelectTopSellers
would not benefit from it. 
</li>
          <li>
If we implement caching in SqlProductRepository, it wouldn’t be available for any
other IProductRepository implementations.</li>
        </ul>
        <p>
Since the premise for this post is that we will <em>never</em> use any other database
than SQL Server, implementing caching directly in SqlProductRepository sounds like
the correct choice, but we would still be violating the SRP, and thus making our code
more difficult to maintain.
</p>
        <p>
A better solution is to introduce a caching <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a> like
this one:
</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 CachingProductRepository\cf0  : \cf2 IProductRepository\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 ICache\cf0  cache;\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IProductRepository\cf0  repository;\par \par     \cf1 public\cf0  CachingProductRepository(\par         \cf2 IProductRepository\cf0  repository, \cf2 ICache\cf0  cache)\par     \{\par         \cf1 if\cf0  (repository == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "repository"\cf0 );\par         \}\par         \cf1 if\cf0  (cache == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "cache"\cf0 );\par         \}\par \par         \cf1 this\cf0 .cache = cache;\par         \cf1 this\cf0 .repository = repository;\par     \}\par \par \cf1     #region\cf0  IProductRepository Members\par \par     \cf1 public\cf0  \cf2 IEnumerable\cf0 &lt;\cf2 Product\cf0 &gt; SelectTopSellers()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .cache\par             .Retrieve&lt;\cf2 IEnumerable\cf0 &lt;\cf2 Product\cf0 &gt;&gt;(\cf3 "topSellers"\cf0 ,\par                 \cf1 this\cf0 .repository.SelectTopSellers);\par     \}\par \par \cf1     #endregion\cf0 \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">CachingProductRepository</span> : <span style="color: #2b91af">IProductRepository</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">ICache</span> cache;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IProductRepository</span> repository;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> CachingProductRepository(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">IProductRepository</span> repository, <span style="color: #2b91af">ICache</span> cache)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (repository
== <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">"repository"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (cache
== <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">"cache"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.cache
= cache;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.repository
= repository;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IProductRepository Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Product</span>&gt;
SelectTopSellers()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.cache</pre>
          <pre style="margin: 0px">            .Retrieve&lt;<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Product</span>&gt;&gt;(<span style="color: #a31515">"topSellers"</span>,</pre>
          <pre style="margin: 0px">                <span style="color: blue">this</span>.repository.SelectTopSellers);</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>
For completeness sake is here the definition of ICache:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 interface\cf0  \cf2 ICache\cf0 \par \{\par     T Retrieve&lt;T&gt;(\cf1 string\cf0  key, \cf2 Func\cf0 &lt;T&gt; readThrough);\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">ICache</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    T Retrieve&lt;T&gt;(<span style="color: blue">string</span> key, <span style="color: #2b91af">Func</span>&lt;T&gt;
readThrough);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The point is that CachingProductRepository <em>extends</em> any IProductRepository
we provide to it (including SqlProductRepository) without modifying it. Thus, we have
satisfied both the OCP and the SRP.
</p>
        <p>
Just to drive home the point, let us assume that we also wish to record execution
times for various methods for purposes of SLA compliance. We can do this by introducing
yet another Decorator:
</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 PerformanceMeasuringProductRepository\cf0  : \par     \cf2 IProductRepository\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IProductRepository\cf0  repository;\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IStopwatch\cf0  stopwatch;\par \par     \cf1 public\cf0  PerformanceMeasuringProductRepository(\par         \cf2 IProductRepository\cf0  repository, \par         \cf2 IStopwatch\cf0  stopwatch)\par     \{\par         \cf1 if\cf0  (repository == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "repository"\cf0 );\par         \}\par         \cf1 if\cf0  (stopwatch == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "stopwatch"\cf0 );\par         \}\par         \par         \cf1 this\cf0 .repository = repository;\par         \cf1 this\cf0 .stopwatch = stopwatch;\par     \}\par \par \cf1     #region\cf0  IProductRepository Members\par \par     \cf1 public\cf0  \cf2 IEnumerable\cf0 &lt;\cf2 Product\cf0 &gt; SelectTopSellers()\par     \{\par         \cf1 var\cf0  timer = \cf1 this\cf0 .stopwatch\par             .StartMeasuring(\cf3 "SelectTopSellers"\cf0 );\par         \cf1 var\cf0  topSellers = \par             \cf1 this\cf0 .repository.SelectTopSellers();\par         timer.StopMeasuring();\par         \cf1 return\cf0  topSellers;\par     \}\par \par \cf1     #endregion\cf0 \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">PerformanceMeasuringProductRepository</span> : </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IProductRepository</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">IProductRepository</span> repository;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IStopwatch</span> stopwatch;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> PerformanceMeasuringProductRepository(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">IProductRepository</span> repository, </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">IStopwatch</span> stopwatch)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (repository
== <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">"repository"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (stopwatch
== <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">"stopwatch"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.repository
= repository;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.stopwatch
= stopwatch;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IProductRepository Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">Product</span>&gt;
SelectTopSellers()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> timer
= <span style="color: blue">this</span>.stopwatch</pre>
          <pre style="margin: 0px">            .StartMeasuring(<span style="color: #a31515">"SelectTopSellers"</span>);</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> topSellers
= </pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.repository.SelectTopSellers();</pre>
          <pre style="margin: 0px">        timer.StopMeasuring();</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> topSellers;</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>
Once again, we modified neither SqlProductRepository nor CachingProductRepository
to introduce this new feature. We can implement security and auditing features by
following the same principle.
</p>
        <p>
To me, this is what loose coupling (and DI) is all about. That we can also replace
data access components and unit test using dynamic mocks are very fortunate side effects,
but the loose coupling is valuable in itself because it enables us to write more maintainable
code.
</p>
        <p>
We don’t even need a DI Container to wire up all these repositories (although it sure
would be helpful). Here’s how we can do it with Poor Man’s DI:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;}\f0 \fs19 \cf1 IProductRepository\cf0  repository =\par     \cf2 new\cf0  \cf1 PerformanceMeasuringProductRepository\cf0 (\par         \cf2 new\cf0  \cf1 CachingProductRepository\cf0 (\par             \cf2 new\cf0  \cf1 SqlProductRepository\cf0 (), \cf2 new\cf0  \cf1 Cache\cf0 ()\par             ),\par         \cf2 new\cf0  \cf1 RealStopwatch\cf0 ()\par     );\par \cf2 var\cf0  vm = \cf2 new\cf0  \cf1 Pr\uinput1\u233 &#233;cisViewModel\cf0 (repository);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">IProductRepository</span> repository
=</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">PerformanceMeasuringProductRepository</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">CachingProductRepository</span>(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">SqlProductRepository</span>(), <span style="color: blue">new</span><span style="color: #2b91af">Cache</span>()</pre>
          <pre style="margin: 0px">            ),</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">RealStopwatch</span>()</pre>
          <pre style="margin: 0px">    );</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> vm
= <span style="color: blue">new</span><span style="color: #2b91af">PrécisViewModel</span>(repository);</pre>
        </div>
        <p>
The next time someone on your team claims that you don’t need DI because the choice
of RDBMS is fixed, you can tell them that it’s irrelevant. The choice is between DI
and Spaghetti Code.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=002cb292-46c0-4090-83e2-0bdec32b25b4" />
      </body>
      <title>Dependency Injection is Loose Coupling</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,002cb292-46c0-4090-83e2-0bdec32b25b4.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/07/DependencyInjectionIsLooseCoupling.aspx</link>
      <pubDate>Wed, 07 Apr 2010 19:49:11 GMT</pubDate>
      <description>&lt;p&gt;
It seems to me that I’ve lately encountered a particular mindset towards Dependency
Injection (DI). People seem to think that it’s only really good for replacing one
data access implementation with another. Once you get to that point, you know that
the following argument isn’t far behind:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
“That’s all well and good, but we know for certain that we will &lt;em&gt;never&lt;/em&gt; exchange
[insert name of RDBMS here] with anything else in this application.”
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Apart from the hubris of making such a bold statement about the future of any software
endeavor, such a statement reveals the narrow view on DI that its only purpose is
for replacing data access components – and perhaps for unit testing.
&lt;/p&gt;
&lt;p&gt;
Those are relevant reasons for using DI, but they are only &lt;em&gt;some&lt;/em&gt; of the reasons.
Let’s briefly revisit why we employ DI.
&lt;/p&gt;
&lt;p&gt;
We use DI to enable loose coupling.
&lt;/p&gt;
&lt;p&gt;
DI is only a means to an end. Even if you &lt;em&gt;never&lt;/em&gt; intend to replace your database
and even if you never want to write a single unit test, DI still offers benefits in
form of a more maintainable code base. The loose coupling gives you better separation
of concerns because it allows you to apply the &lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open/Closed
Principle&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Example coming right up:
&lt;/p&gt;
&lt;p&gt;
Imagine that we need to implement a PrécisViewModel class with a TopSellers property
that returns an IEnumerable&amp;lt;string&amp;gt;. To implement this class, we have a data
access component. Let’s use the ubiquitous Repository pattern and define IProductRepository
to see where that leads us:
&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 IProductRepository\cf0 \par \{\par     \cf2 IEnumerable\cf0 &amp;lt;\cf2 Product\cf0 &amp;gt; SelectTopSellers();\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;IProductRepository&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: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Product&lt;/span&gt;&amp;gt;
SelectTopSellers();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We can now implement PrécisViewModel like this:
&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 Pr\uinput1\u233 &amp;#233;cisViewModel\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IProductRepository\cf0  repository;\par \par     \cf1 public\cf0  Pr\uinput1\u233 &amp;#233;cisViewModel(\cf2 IProductRepository\cf0  repository)\par     \{\par         \cf1 if\cf0  (repository == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "repository"\cf0 );\par         \}\par \par         \cf1 this\cf0 .repository = repository;\par     \}\par \par     \cf1 public\cf0  \cf2 IEnumerable\cf0 &amp;lt;\cf1 string\cf0 &amp;gt; TopSellers\par     \{\par         \cf1 get\cf0 \par         \{\par             \cf1 var\cf0  topSellers = \par                 \cf1 this\cf0 .repository.SelectTopSellers();\par             \cf1 return\cf0  \cf1 from\cf0  p \cf1 in\cf0  topSellers\par                    \cf1 select\cf0  p.Name;\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;PrécisViewModel&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;IProductRepository&lt;/span&gt; repository;&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; PrécisViewModel(&lt;span style="color: #2b91af"&gt;IProductRepository&lt;/span&gt; repository)&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; (repository
== &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;"repository"&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;.repository
= repository;&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;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;
TopSellers&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;/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; topSellers
= &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;.repository.SelectTopSellers();&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;return&lt;/span&gt; &lt;span style="color: blue"&gt;from&lt;/span&gt; p &lt;span style="color: blue"&gt;in&lt;/span&gt; topSellers&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; &lt;span style="color: blue"&gt;select&lt;/span&gt; p.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;/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;
Nothing fancy is going on here. It’s just straight Constructor Injection at work.
&lt;/p&gt;
&lt;p&gt;
Obviously, we can now implement and use a SQL Server-based repository:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  repository = \cf1 new\cf0  \cf2 SqlProductRepository\cf0 ();\par \cf1 var\cf0  vm = \cf1 new\cf0  \cf2 Pr\uinput1\u233 &amp;#233;cisViewModel\cf0 (repository);\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; repository
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SqlProductRepository&lt;/span&gt;();&lt;/pre&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;PrécisViewModel&lt;/span&gt;(repository);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
So what does all this loose coupling buy us? It doesn’t seem to help us a lot.
&lt;/p&gt;
&lt;p&gt;
The real benefit is not yet apparent, but it should become more obvious when we start
adding requirements. Let’s start with some caching. It turns out that the SelectTopSellers
implementation is slow, so we would like to add some caching somewhere.
&lt;/p&gt;
&lt;p&gt;
Where should we add this caching functionality? Without loose coupling, we would more
or less be constrained to adding it to either PrécisViewModel or SqlProductRepository,
but both have issues:
&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;
First of all we would be violating the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt; (SRP) in both cases. 
&lt;li&gt;
If we implement caching in PrécisViewModel, other consumers of the SelectTopSellers
would not benefit from it. 
&lt;li&gt;
If we implement caching in SqlProductRepository, it wouldn’t be available for any
other IProductRepository implementations.&lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;
Since the premise for this post is that we will &lt;em&gt;never&lt;/em&gt; use any other database
than SQL Server, implementing caching directly in SqlProductRepository sounds like
the correct choice, but we would still be violating the SRP, and thus making our code
more difficult to maintain.
&lt;/p&gt;
&lt;p&gt;
A better solution is to introduce a caching &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorator&lt;/a&gt; like
this one:
&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 CachingProductRepository\cf0  : \cf2 IProductRepository\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 ICache\cf0  cache;\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IProductRepository\cf0  repository;\par \par     \cf1 public\cf0  CachingProductRepository(\par         \cf2 IProductRepository\cf0  repository, \cf2 ICache\cf0  cache)\par     \{\par         \cf1 if\cf0  (repository == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "repository"\cf0 );\par         \}\par         \cf1 if\cf0  (cache == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "cache"\cf0 );\par         \}\par \par         \cf1 this\cf0 .cache = cache;\par         \cf1 this\cf0 .repository = repository;\par     \}\par \par \cf1     #region\cf0  IProductRepository Members\par \par     \cf1 public\cf0  \cf2 IEnumerable\cf0 &amp;lt;\cf2 Product\cf0 &amp;gt; SelectTopSellers()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .cache\par             .Retrieve&amp;lt;\cf2 IEnumerable\cf0 &amp;lt;\cf2 Product\cf0 &amp;gt;&amp;gt;(\cf3 "topSellers"\cf0 ,\par                 \cf1 this\cf0 .repository.SelectTopSellers);\par     \}\par \par \cf1     #endregion\cf0 \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;CachingProductRepository&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IProductRepository&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;ICache&lt;/span&gt; cache;&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;IProductRepository&lt;/span&gt; repository;&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; CachingProductRepository(&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;IProductRepository&lt;/span&gt; repository, &lt;span style="color: #2b91af"&gt;ICache&lt;/span&gt; cache)&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; (repository
== &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;"repository"&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; (cache
== &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;"cache"&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;.cache
= cache;&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;.repository
= repository;&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; IProductRepository 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: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Product&lt;/span&gt;&amp;gt;
SelectTopSellers()&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: blue"&gt;this&lt;/span&gt;.cache&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; .Retrieve&amp;lt;&lt;span style="color: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Product&lt;/span&gt;&amp;gt;&amp;gt;(&lt;span style="color: #a31515"&gt;"topSellers"&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;.repository.SelectTopSellers);&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;
For completeness sake is here the definition of ICache:
&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 ICache\cf0 \par \{\par     T Retrieve&amp;lt;T&amp;gt;(\cf1 string\cf0  key, \cf2 Func\cf0 &amp;lt;T&amp;gt; readThrough);\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;ICache&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 Retrieve&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;string&lt;/span&gt; key, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
readThrough);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The point is that CachingProductRepository &lt;em&gt;extends&lt;/em&gt; any IProductRepository
we provide to it (including SqlProductRepository) without modifying it. Thus, we have
satisfied both the OCP and the SRP.
&lt;/p&gt;
&lt;p&gt;
Just to drive home the point, let us assume that we also wish to record execution
times for various methods for purposes of SLA compliance. We can do this by introducing
yet another Decorator:
&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 PerformanceMeasuringProductRepository\cf0  : \par     \cf2 IProductRepository\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IProductRepository\cf0  repository;\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IStopwatch\cf0  stopwatch;\par \par     \cf1 public\cf0  PerformanceMeasuringProductRepository(\par         \cf2 IProductRepository\cf0  repository, \par         \cf2 IStopwatch\cf0  stopwatch)\par     \{\par         \cf1 if\cf0  (repository == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "repository"\cf0 );\par         \}\par         \cf1 if\cf0  (stopwatch == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "stopwatch"\cf0 );\par         \}\par         \par         \cf1 this\cf0 .repository = repository;\par         \cf1 this\cf0 .stopwatch = stopwatch;\par     \}\par \par \cf1     #region\cf0  IProductRepository Members\par \par     \cf1 public\cf0  \cf2 IEnumerable\cf0 &amp;lt;\cf2 Product\cf0 &amp;gt; SelectTopSellers()\par     \{\par         \cf1 var\cf0  timer = \cf1 this\cf0 .stopwatch\par             .StartMeasuring(\cf3 "SelectTopSellers"\cf0 );\par         \cf1 var\cf0  topSellers = \par             \cf1 this\cf0 .repository.SelectTopSellers();\par         timer.StopMeasuring();\par         \cf1 return\cf0  topSellers;\par     \}\par \par \cf1     #endregion\cf0 \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;PerformanceMeasuringProductRepository&lt;/span&gt; : &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IProductRepository&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;IProductRepository&lt;/span&gt; repository;&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;IStopwatch&lt;/span&gt; stopwatch;&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; PerformanceMeasuringProductRepository(&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;IProductRepository&lt;/span&gt; repository, &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;IStopwatch&lt;/span&gt; stopwatch)&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; (repository
== &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;"repository"&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; (stopwatch
== &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;"stopwatch"&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;.repository
= repository;&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;.stopwatch
= stopwatch;&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; IProductRepository 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: #2b91af"&gt;IEnumerable&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Product&lt;/span&gt;&amp;gt;
SelectTopSellers()&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; timer
= &lt;span style="color: blue"&gt;this&lt;/span&gt;.stopwatch&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; .StartMeasuring(&lt;span style="color: #a31515"&gt;"SelectTopSellers"&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;var&lt;/span&gt; topSellers
= &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;.repository.SelectTopSellers();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; timer.StopMeasuring();&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; topSellers;&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;
Once again, we modified neither SqlProductRepository nor CachingProductRepository
to introduce this new feature. We can implement security and auditing features by
following the same principle.
&lt;/p&gt;
&lt;p&gt;
To me, this is what loose coupling (and DI) is all about. That we can also replace
data access components and unit test using dynamic mocks are very fortunate side effects,
but the loose coupling is valuable in itself because it enables us to write more maintainable
code.
&lt;/p&gt;
&lt;p&gt;
We don’t even need a DI Container to wire up all these repositories (although it sure
would be helpful). Here’s how we can do it with Poor Man’s DI:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red43\green145\blue175;\red0\green0\blue255;}\f0 \fs19 \cf1 IProductRepository\cf0  repository =\par     \cf2 new\cf0  \cf1 PerformanceMeasuringProductRepository\cf0 (\par         \cf2 new\cf0  \cf1 CachingProductRepository\cf0 (\par             \cf2 new\cf0  \cf1 SqlProductRepository\cf0 (), \cf2 new\cf0  \cf1 Cache\cf0 ()\par             ),\par         \cf2 new\cf0  \cf1 RealStopwatch\cf0 ()\par     );\par \cf2 var\cf0  vm = \cf2 new\cf0  \cf1 Pr\uinput1\u233 &amp;#233;cisViewModel\cf0 (repository);\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: #2b91af"&gt;IProductRepository&lt;/span&gt; repository
=&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;PerformanceMeasuringProductRepository&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;CachingProductRepository&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;SqlProductRepository&lt;/span&gt;(), &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Cache&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;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;RealStopwatch&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;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;PrécisViewModel&lt;/span&gt;(repository);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The next time someone on your team claims that you don’t need DI because the choice
of RDBMS is fixed, you can tell them that it’s irrelevant. The choice is between DI
and Spaghetti Code.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=002cb292-46c0-4090-83e2-0bdec32b25b4" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,002cb292-46c0-4090-83e2-0bdec32b25b4.aspx</comments>
      <category>Dependency Injection</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=a19c5021-1467-40fe-b0fd-c276fde0713e</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,a19c5021-1467-40fe-b0fd-c276fde0713e.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,a19c5021-1467-40fe-b0fd-c276fde0713e.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=a19c5021-1467-40fe-b0fd-c276fde0713e</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my <a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx">previous</a><a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx">posts</a> I
demonstrated interaction-based unit tests that verify that a pizza is correctly being
added to a shopping basket. An alternative is a state-based test where we examine
the contents of the shopping basket after exercising the <a href="http://xunitpatterns.com/SUT.html">SUT</a>.
Here’s an initial attempt:
</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  AddWillAddToBasket()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    fixture.Register&lt;\cf3 IPizzaMap\cf0 &gt;(\par ??        fixture.CreateAnonymous&lt;\cf3 PizzaMap\cf0 &gt;);\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&lt;\cf3 Basket\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&lt;\cf3 PizzaPresenter\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 BasketPresenter\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .IsTrue(basket.Pizze.Any(p =&gt; \par ??        p.Name == pizza.Name), \cf6 "Basket has added pizza."\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> AddWillAddToBasket()</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.Register&lt;<span style="color: #2b91af">IPizzaMap</span>&gt;(</pre>
          <pre style="margin: 0px">        fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaMap</span>&gt;);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> basket
= fixture.Freeze&lt;<span style="color: #2b91af">Basket</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> pizza
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaPresenter</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">BasketPresenter</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.Add(pizza);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.IsTrue(basket.Pizze.Any(p
=&gt; </pre>
          <pre style="margin: 0px">        p.Name == pizza.Name), <span style="color: #a31515">"Basket
has added pizza."</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this case the assertion examines the Pizze collection (you did know that the plural
of <em>pizza</em> is <em>pizze</em>, right?) of the <a href="http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze.aspx">frozen
Basket</a> to verify that it contains the added pizza.
</p>
        <p>
The tricky part is that the Pizze property is a collection of Pizza instances, and
not PizzaPresenter instances. The injected IPizzaMap instance is responsible for mapping
from PizzaPresenter to Pizza, but since we are rewriting this as a state-based test,
I thought it would also be interesting to write the test without using <a href="http://code.google.com/p/moq/">Moq</a>.
Instead, we can use the real implementation of IPizzaMap, but this means that we must
instruct <a href="http://autofixture.codeplex.com/">AutoFixture</a> to map from the
abstract IPizzaMap to the concrete PizzaMap.
</p>
        <p>
We see that happening in this line of code:
</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.Register&lt;\cf3 IPizzaMap\cf0 &gt;(\par ??    fixture.CreateAnonymous&lt;\cf3 PizzaMap\cf0 &gt;);}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">fixture.Register&lt;<span style="color: #2b91af">IPizzaMap</span>&gt;(</pre>
          <pre style="margin: 0px">    fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaMap</span>&gt;);</pre>
        </div>
        <p>
Notice the method group syntax: we pass in a delegate to the CreateAnonymous method,
which means that every time the fixture is asked to create an IPizzaMap instance,
it invokes CreateAnonymous&lt;PIzzaMap&gt;() and uses the result.
</p>
        <p>
This is, obviously, a general-purpose way in which we can map compatible types, so
we can write an extension method like this one:
</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 void\cf0  Register&lt;TAbstract, TConcrete&gt;(\par ??    \cf1 this\cf0  \cf4 Fixture\cf0  fixture) \cf1 where\cf0  TConcrete : TAbstract\par ??\{\par ??    fixture.Register&lt;TAbstract&gt;(() =&gt;\par ??        fixture.CreateAnonymous&lt;TConcrete&gt;());\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">void</span> Register&lt;TAbstract,
TConcrete&gt;(</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span><span style="color: #2b91af">Fixture</span> fixture) <span style="color: blue">where</span> TConcrete
: TAbstract</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    fixture.Register&lt;TAbstract&gt;(() =&gt;</pre>
          <pre style="margin: 0px">        fixture.CreateAnonymous&lt;TConcrete&gt;());</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
(I’m slightly undecided on the name of this method. <em>Map</em> might be a better
name, but I just like the equivalence to some common DI Containers and their Register
methods.) Armed with this Register overload, we can now rewrite the previous Register
statement 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;}??\fs20 fixture.Register&lt;\cf3 IPizzaMap\cf0 , \cf3 PizzaMap\cf0 &gt;();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">fixture.Register&lt;<span style="color: #2b91af">IPizzaMap</span>, <span style="color: #2b91af">PizzaMap</span>&gt;();</pre>
        </div>
        <p>
It’s the same amount of code lines, but I find it slightly more succinct and communicative.
</p>
        <p>
The real point of this blog post, however, is that you can map abstract types to concrete
types, and that you can always write extension methods to encapsulate your own AutoFixture
idioms.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a19c5021-1467-40fe-b0fd-c276fde0713e" />
      </body>
      <title>Mapping types with AutoFixture</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,a19c5021-1467-40fe-b0fd-c276fde0713e.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/06/MappingTypesWithAutoFixture.aspx</link>
      <pubDate>Tue, 06 Apr 2010 05:22:32 GMT</pubDate>
      <description>&lt;p&gt;
In my &lt;a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx"&gt;previous&lt;/a&gt; &lt;a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx"&gt;posts&lt;/a&gt; I
demonstrated interaction-based unit tests that verify that a pizza is correctly being
added to a shopping basket. An alternative is a state-based test where we examine
the contents of the shopping basket after exercising the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;.
Here’s an initial attempt:
&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  AddWillAddToBasket()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    fixture.Register&amp;lt;\cf3 IPizzaMap\cf0 &amp;gt;(\par ??        fixture.CreateAnonymous&amp;lt;\cf3 PizzaMap\cf0 &amp;gt;);\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&amp;lt;\cf3 Basket\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&amp;lt;\cf3 PizzaPresenter\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 BasketPresenter\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .IsTrue(basket.Pizze.Any(p =&amp;gt; \par ??        p.Name == pizza.Name), \cf6 "Basket has added pizza."\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; AddWillAddToBasket()&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.Register&amp;lt;&lt;span style="color: #2b91af"&gt;IPizzaMap&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; fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaMap&lt;/span&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;var&lt;/span&gt; basket
= fixture.Freeze&amp;lt;&lt;span style="color: #2b91af"&gt;Basket&lt;/span&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;var&lt;/span&gt; pizza
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaPresenter&lt;/span&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;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;BasketPresenter&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; sut.Add(pizza);&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(basket.Pizze.Any(p
=&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; p.Name == pizza.Name), &lt;span style="color: #a31515"&gt;"Basket
has added pizza."&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 case the assertion examines the Pizze collection (you did know that the plural
of &lt;em&gt;pizza&lt;/em&gt; is &lt;em&gt;pizze&lt;/em&gt;, right?) of the &lt;a href="http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze.aspx"&gt;frozen
Basket&lt;/a&gt; to verify that it contains the added pizza.
&lt;/p&gt;
&lt;p&gt;
The tricky part is that the Pizze property is a collection of Pizza instances, and
not PizzaPresenter instances. The injected IPizzaMap instance is responsible for mapping
from PizzaPresenter to Pizza, but since we are rewriting this as a state-based test,
I thought it would also be interesting to write the test without using &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt;.
Instead, we can use the real implementation of IPizzaMap, but this means that we must
instruct &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; to map from the
abstract IPizzaMap to the concrete PizzaMap.
&lt;/p&gt;
&lt;p&gt;
We see that happening in this line of code:
&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.Register&amp;lt;\cf3 IPizzaMap\cf0 &amp;gt;(\par ??    fixture.CreateAnonymous&amp;lt;\cf3 PizzaMap\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;fixture.Register&amp;lt;&lt;span style="color: #2b91af"&gt;IPizzaMap&lt;/span&gt;&amp;gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaMap&lt;/span&gt;&amp;gt;);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice the method group syntax: we pass in a delegate to the CreateAnonymous method,
which means that every time the fixture is asked to create an IPizzaMap instance,
it invokes CreateAnonymous&amp;lt;PIzzaMap&amp;gt;() and uses the result.
&lt;/p&gt;
&lt;p&gt;
This is, obviously, a general-purpose way in which we can map compatible types, so
we can write an extension method like this one:
&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 void\cf0  Register&amp;lt;TAbstract, TConcrete&amp;gt;(\par ??    \cf1 this\cf0  \cf4 Fixture\cf0  fixture) \cf1 where\cf0  TConcrete : TAbstract\par ??\{\par ??    fixture.Register&amp;lt;TAbstract&amp;gt;(() =&amp;gt;\par ??        fixture.CreateAnonymous&amp;lt;TConcrete&amp;gt;());\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;void&lt;/span&gt; Register&amp;lt;TAbstract,
TConcrete&amp;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; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt; fixture) &lt;span style="color: blue"&gt;where&lt;/span&gt; TConcrete
: TAbstract&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Register&amp;lt;TAbstract&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; fixture.CreateAnonymous&amp;lt;TConcrete&amp;gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
(I’m slightly undecided on the name of this method. &lt;em&gt;Map&lt;/em&gt; might be a better
name, but I just like the equivalence to some common DI Containers and their Register
methods.) Armed with this Register overload, we can now rewrite the previous Register
statement 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;}??\fs20 fixture.Register&amp;lt;\cf3 IPizzaMap\cf0 , \cf3 PizzaMap\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;fixture.Register&amp;lt;&lt;span style="color: #2b91af"&gt;IPizzaMap&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;PizzaMap&lt;/span&gt;&amp;gt;();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
It’s the same amount of code lines, but I find it slightly more succinct and communicative.
&lt;/p&gt;
&lt;p&gt;
The real point of this blog post, however, is that you can map abstract types to concrete
types, and that you can always write extension methods to encapsulate your own AutoFixture
idioms.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a19c5021-1467-40fe-b0fd-c276fde0713e" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,a19c5021-1467-40fe-b0fd-c276fde0713e.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=3dcb0700-6139-4d7a-ac48-8ce3950fe42e</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,3dcb0700-6139-4d7a-ac48-8ce3950fe42e.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,3dcb0700-6139-4d7a-ac48-8ce3950fe42e.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=3dcb0700-6139-4d7a-ac48-8ce3950fe42e</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://autofixture.codeplex.com/">AutoFixture</a> 1.1 Release Candidate 1
is now available on the CodePlex site.
</p>
        <p>
Users are encouraged to evaluate this RC and submit feedback. If no bugs or issues
are reported within the next week, we will promote RC1 to version 1.1.
</p>
        <p>
The <a href="http://autofixture.codeplex.com/releases/view/42969">release page</a> has
more details about this particular release.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3dcb0700-6139-4d7a-ac48-8ce3950fe42e" />
      </body>
      <title>AutoFixture 1.1 RC1</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,3dcb0700-6139-4d7a-ac48-8ce3950fe42e.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/02/AutoFixture11RC1.aspx</link>
      <pubDate>Fri, 02 Apr 2010 06:44:27 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; 1.1 Release Candidate 1
is now available on the CodePlex site.
&lt;/p&gt;
&lt;p&gt;
Users are encouraged to evaluate this RC and submit feedback. If no bugs or issues
are reported within the next week, we will promote RC1 to version 1.1.
&lt;/p&gt;
&lt;p&gt;
The &lt;a href="http://autofixture.codeplex.com/releases/view/42969"&gt;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=3dcb0700-6139-4d7a-ac48-8ce3950fe42e" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,3dcb0700-6139-4d7a-ac48-8ce3950fe42e.aspx</comments>
      <category>AutoFixture</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=9930c822-22bc-422d-a437-fb1e81e000a7</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,9930c822-22bc-422d-a437-fb1e81e000a7.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,9930c822-22bc-422d-a437-fb1e81e000a7.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=9930c822-22bc-422d-a437-fb1e81e000a7</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
My <a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx">previous post</a> about <a href="http://autofixture.codeplex.com/">AutoFixture</a>’s
Freeze functionality included this little piece of code that I didn’t discuss:
</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  mapMock = \cf1 new\cf0  \cf4 Mock\cf0 &lt;\cf4 IPizzaMap\cf0 &gt;();\par ??fixture.Register(mapMock.Object);}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mapMock
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">IPizzaMap</span>&gt;();</pre>
          <pre style="margin: 0px">fixture.Register(mapMock.Object);</pre>
        </div>
        <p>
In case you were wondering, this is <a href="http://code.google.com/p/moq/">Moq</a> interacting
with AutoFixture. Here we create a new <a href="http://xunitpatterns.com/Test%20Double.html">Test
Double</a> and register it with the fixture. This is very similar to AutoFixture’s
built-in Freeze functionality, with the difference that we register an IPizzaMap instance,
which isn’t the same as the Mock&lt;IPizzaMap&gt; instance.
</p>
        <p>
It would be nice if we could simply freeze a Test Double emitted by Moq, but unfortunately
we can’t directly use the Freeze method, since Freeze&lt;Mock&lt;IPizzaMap&gt;&gt;()
would freeze a Mock&lt;IPizzaMap&gt;, but not IPizzaMap itself. On the other hand,
Freeze&lt;IPizzaMap&gt;() wouldn’t work because we haven’t told the fixture how to
create IPizzaMap instances, but even if we had, we wouldn’t have a Mock&lt;IPizzaMap&gt;
against which we could call Verify.
</p>
        <p>
On the other hand, it’s trivial to write an extension method to Fixture:
</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  \cf4 Mock\cf0 &lt;T&gt; FreezeMoq&lt;T&gt;(\cf1 this\cf0  \cf4 Fixture\cf0  fixture)\par ??    \cf1 where\cf0  T : \cf1 class\par ??\cf0 \{\par ??    \cf1 var\cf0  td = \cf1 new\cf0  \cf4 Mock\cf0 &lt;T&gt;();\par ??    fixture.Register(td.Object);\par ??    \cf1 return\cf0  td;\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: #2b91af">Mock</span>&lt;T&gt;
FreezeMoq&lt;T&gt;(<span style="color: blue">this</span><span style="color: #2b91af">Fixture</span> fixture)</pre>
          <pre style="margin: 0px">    <span style="color: blue">where</span> T
: <span style="color: blue">class</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> td
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;T&gt;();</pre>
          <pre style="margin: 0px">    fixture.Register(td.Object);</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> td;</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
I chose to call the method FreezeMoq to indicate its affinity with Moq.
</p>
        <p>
We can now rewrite the unit test from the previous post 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;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  AddWillPipeMapCorrectly_FreezeMoq()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&lt;\cf3 Basket\cf0 &gt;();\par ??    \cf4 var\cf0  mapMock = fixture.FreezeMoq&lt;\cf3 IPizzaMap\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&lt;\cf3 PizzaPresenter\cf0 &gt;();\par ??    \par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 BasketPresenter\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     mapMock.Verify(m =&gt; m.Pipe(pizza, basket.Add));\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> AddWillPipeMapCorrectly_FreezeMoq()</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"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> basket
= fixture.Freeze&lt;<span style="color: #2b91af">Basket</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> mapMock
= fixture.FreezeMoq&lt;<span style="color: #2b91af">IPizzaMap</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> pizza
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaPresenter</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">BasketPresenter</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.Add(pizza);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    mapMock.Verify(m =&gt; m.Pipe(pizza, basket.Add));</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
You may think that saving only a single line of code may not be that big a deal, but
if you also need to perform Setups on the Mock, or if you have several different Mocks
to configure, you may appreciate the encapsulation. I know I sure do.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9930c822-22bc-422d-a437-fb1e81e000a7" />
      </body>
      <title>Freezing mocks</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,9930c822-22bc-422d-a437-fb1e81e000a7.aspx</guid>
      <link>http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx</link>
      <pubDate>Sat, 27 Mar 2010 13:27:02 GMT</pubDate>
      <description>&lt;p&gt;
My &lt;a href="http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx"&gt;previous post&lt;/a&gt; about &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;’s
Freeze functionality included this little piece of code that I didn’t discuss:
&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  mapMock = \cf1 new\cf0  \cf4 Mock\cf0 &amp;lt;\cf4 IPizzaMap\cf0 &amp;gt;();\par ??fixture.Register(mapMock.Object);}
--&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; mapMock
= &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;IPizzaMap&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.Register(mapMock.Object);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In case you were wondering, this is &lt;a href="http://code.google.com/p/moq/"&gt;Moq&lt;/a&gt; interacting
with AutoFixture. Here we create a new &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test
Double&lt;/a&gt; and register it with the fixture. This is very similar to AutoFixture’s
built-in Freeze functionality, with the difference that we register an IPizzaMap instance,
which isn’t the same as the Mock&amp;lt;IPizzaMap&amp;gt; instance.
&lt;/p&gt;
&lt;p&gt;
It would be nice if we could simply freeze a Test Double emitted by Moq, but unfortunately
we can’t directly use the Freeze method, since Freeze&amp;lt;Mock&amp;lt;IPizzaMap&amp;gt;&amp;gt;()
would freeze a Mock&amp;lt;IPizzaMap&amp;gt;, but not IPizzaMap itself. On the other hand,
Freeze&amp;lt;IPizzaMap&amp;gt;() wouldn’t work because we haven’t told the fixture how to
create IPizzaMap instances, but even if we had, we wouldn’t have a Mock&amp;lt;IPizzaMap&amp;gt;
against which we could call Verify.
&lt;/p&gt;
&lt;p&gt;
On the other hand, it’s trivial to write an extension method to Fixture:
&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  \cf4 Mock\cf0 &amp;lt;T&amp;gt; FreezeMoq&amp;lt;T&amp;gt;(\cf1 this\cf0  \cf4 Fixture\cf0  fixture)\par ??    \cf1 where\cf0  T : \cf1 class\par ??\cf0 \{\par ??    \cf1 var\cf0  td = \cf1 new\cf0  \cf4 Mock\cf0 &amp;lt;T&amp;gt;();\par ??    fixture.Register(td.Object);\par ??    \cf1 return\cf0  td;\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: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;T&amp;gt;
FreezeMoq&amp;lt;T&amp;gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Fixture&lt;/span&gt; fixture)&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: blue"&gt;class&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;var&lt;/span&gt; td
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;T&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Register(td.Object);&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; td;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I chose to call the method FreezeMoq to indicate its affinity with Moq.
&lt;/p&gt;
&lt;p&gt;
We can now rewrite the unit test from the previous post 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;}??\fs20 [\cf3 TestMethod\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  AddWillPipeMapCorrectly_FreezeMoq()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&amp;lt;\cf3 Basket\cf0 &amp;gt;();\par ??    \cf4 var\cf0  mapMock = fixture.FreezeMoq&amp;lt;\cf3 IPizzaMap\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&amp;lt;\cf3 PizzaPresenter\cf0 &amp;gt;();\par ??    \par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 BasketPresenter\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     mapMock.Verify(m =&amp;gt; m.Pipe(pizza, basket.Add));\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; AddWillPipeMapCorrectly_FreezeMoq()&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;&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; basket
= fixture.Freeze&amp;lt;&lt;span style="color: #2b91af"&gt;Basket&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;var&lt;/span&gt; mapMock
= fixture.FreezeMoq&amp;lt;&lt;span style="color: #2b91af"&gt;IPizzaMap&lt;/span&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;var&lt;/span&gt; pizza
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaPresenter&lt;/span&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;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;BasketPresenter&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; sut.Add(pizza);&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; mapMock.Verify(m =&amp;gt; m.Pipe(pizza, basket.Add));&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 may think that saving only a single line of code may not be that big a deal, but
if you also need to perform Setups on the Mock, or if you have several different Mocks
to configure, you may appreciate the encapsulation. I know I sure do.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9930c822-22bc-422d-a437-fb1e81e000a7" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,9930c822-22bc-422d-a437-fb1e81e000a7.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=0b36f631-086d-4d79-a1ad-5153716987b0</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,0b36f631-086d-4d79-a1ad-5153716987b0.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,0b36f631-086d-4d79-a1ad-5153716987b0.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=0b36f631-086d-4d79-a1ad-5153716987b0</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my <a href="http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze.aspx">previous blog
post</a>, I introduced <a href="http://autofixture.codeplex.com/">AutoFixture</a>’s
Freeze feature, but the example didn’t fully demonstrate the power of the concept.
In this blog post, we will turn up the heat on the frozen pizza a notch.
</p>
        <p>
The following unit test exercises the BasketPresenter class, which is simply a wrapper
around a Basket instance (we’re doing a pizza online shop, if you were wondering).
In true TDD style, I’ll start with the unit test, but I’ll post the BasketPresenter
class later for reference.
</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  AddWillPipeMapCorrectly()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&lt;\cf3 Basket\cf0 &gt;();\par ??\par ??    \cf4 var\cf0  mapMock = \cf4 new\cf0  \cf3 Mock\cf0 &lt;\cf3 IPizzaMap\cf0 &gt;();\par ??    fixture.Register(mapMock.Object);\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&lt;\cf3 PizzaPresenter\cf0 &gt;();\par ??    \par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 BasketPresenter\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     mapMock.Verify(m =&gt; m.Pipe(pizza, basket.Add));\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> AddWillPipeMapCorrectly()</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"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> basket
= fixture.Freeze&lt;<span style="color: #2b91af">Basket</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> mapMock
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">IPizzaMap</span>&gt;();</pre>
          <pre style="margin: 0px">    fixture.Register(mapMock.Object);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> pizza
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">PizzaPresenter</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">BasketPresenter</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Exercise system</span></pre>
          <pre style="margin: 0px">    sut.Add(pizza);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    mapMock.Verify(m =&gt; m.Pipe(pizza, basket.Add));</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The interesting thing in the above unit test is that we Freeze a Basket instance in
the fixture. We do this because we know that the BasketPresenter <em>somehow</em> wraps
a Basket instance, but we trust the Fixture class to figure it out for us. By telling
the fixture instance to Freeze the Basket we know that it will reuse the same Basket
instance throughout the entire test case. That includes the call to CreateAnonymous&lt;BasketPresenter&gt;.
</p>
        <p>
This means that we can use the frozen basket instance in the Verify call because we
know that the same instance will have been reused by the fixture, and thus wrapped
by the <a href="http://xunitpatterns.com/SUT.html">SUT</a>.
</p>
        <p>
When you stop to think about this on a more theoretical level, it fortunately makes
a lot of sense. AutoFixture’s terminology is based upon the excellent book <a href="http://xunitpatterns.com/">xUnit
Test Patterns</a>, and a Fixture instance pretty much corresponds to the concept of
a <a href="http://xunitpatterns.com/test%20fixture%20-%20xUnit.html">Fixture</a>.
This means that freezing an instance simply means that a particular instance is constant
throughout that particular fixture. Every time we ask for an instance of that class,
we get back the same frozen instance.
</p>
        <p>
In DI Container terminology, we just changed the Basket type’s lifetime behavior from
Transient to Singleton.
</p>
        <p>
For reference, here’s the BasketPresenter class we’re testing:
</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 BasketPresenter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 Basket\cf0  basket;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IPizzaMap\cf0  map;\par ??\par ??    \cf1 public\cf0  BasketPresenter(\cf4 Basket\cf0  basket, \cf4 IPizzaMap\cf0  map)\par ??    \{\par ??        \cf1 if\cf0  (basket == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "basket"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (map == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "map"\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .basket = basket;\par ??        \cf1 this\cf0 .map = map;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Add(\cf4 PizzaPresenter\cf0  presenter)\par ??    \{\par ??        \cf1 this\cf0 .map.Pipe(presenter, \cf1 this\cf0 .basket.Add);\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">BasketPresenter</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">Basket</span> basket;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IPizzaMap</span> map;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> BasketPresenter(<span style="color: #2b91af">Basket</span> basket, <span style="color: #2b91af">IPizzaMap</span> map)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (basket
== <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">"basket"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (map
== <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">"map"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.basket
= basket;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.map
= map;</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> Add(<span style="color: #2b91af">PizzaPresenter</span> presenter)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.map.Pipe(presenter, <span style="color: blue">this</span>.basket.Add);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
If you are wondering about why this is interesting at all, and why we don’t just pass
in a Basket through the BasketPresenter’s constructor, it’s because we are using AutoFixture
as a <a href="http://blog.ploeh.dk/2009/02/13/SUTFactory.aspx">SUT Factory</a>. We
want to be able to refactor BasketPresenter (and in this case particularly its constructor)
without breaking a lot of existing tests. The level of indirection provided by AutoFixture
gives us just that ability because we never directly invoke the constructor.
</p>
        <p>
Coming up: <a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx">more fun with
the Freeze concept</a>!
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0b36f631-086d-4d79-a1ad-5153716987b0" />
      </body>
      <title>More about frozen pizza</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,0b36f631-086d-4d79-a1ad-5153716987b0.aspx</guid>
      <link>http://blog.ploeh.dk/2010/03/26/MoreAboutFrozenPizza.aspx</link>
      <pubDate>Fri, 26 Mar 2010 22:01:42 GMT</pubDate>
      <description>&lt;p&gt;
In my &lt;a href="http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze.aspx"&gt;previous blog
post&lt;/a&gt;, I introduced &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;’s
Freeze feature, but the example didn’t fully demonstrate the power of the concept.
In this blog post, we will turn up the heat on the frozen pizza a notch.
&lt;/p&gt;
&lt;p&gt;
The following unit test exercises the BasketPresenter class, which is simply a wrapper
around a Basket instance (we’re doing a pizza online shop, if you were wondering).
In true TDD style, I’ll start with the unit test, but I’ll post the BasketPresenter
class later for reference.
&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  AddWillPipeMapCorrectly()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??\par ??    \cf4 var\cf0  basket = fixture.Freeze&amp;lt;\cf3 Basket\cf0 &amp;gt;();\par ??\par ??    \cf4 var\cf0  mapMock = \cf4 new\cf0  \cf3 Mock\cf0 &amp;lt;\cf3 IPizzaMap\cf0 &amp;gt;();\par ??    fixture.Register(mapMock.Object);\par ??\par ??    \cf4 var\cf0  pizza = fixture.CreateAnonymous&amp;lt;\cf3 PizzaPresenter\cf0 &amp;gt;();\par ??    \par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 BasketPresenter\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     sut.Add(pizza);\par ??    \cf5 // Verify outcome\par ??\cf0     mapMock.Verify(m =&amp;gt; m.Pipe(pizza, basket.Add));\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; AddWillPipeMapCorrectly()&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;&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; basket
= fixture.Freeze&amp;lt;&lt;span style="color: #2b91af"&gt;Basket&lt;/span&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;var&lt;/span&gt; mapMock
= &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;IPizzaMap&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Register(mapMock.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; pizza
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;PizzaPresenter&lt;/span&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;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;BasketPresenter&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; sut.Add(pizza);&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; mapMock.Verify(m =&amp;gt; m.Pipe(pizza, basket.Add));&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 interesting thing in the above unit test is that we Freeze a Basket instance in
the fixture. We do this because we know that the BasketPresenter &lt;em&gt;somehow&lt;/em&gt; wraps
a Basket instance, but we trust the Fixture class to figure it out for us. By telling
the fixture instance to Freeze the Basket we know that it will reuse the same Basket
instance throughout the entire test case. That includes the call to CreateAnonymous&amp;lt;BasketPresenter&amp;gt;.
&lt;/p&gt;
&lt;p&gt;
This means that we can use the frozen basket instance in the Verify call because we
know that the same instance will have been reused by the fixture, and thus wrapped
by the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
When you stop to think about this on a more theoretical level, it fortunately makes
a lot of sense. AutoFixture’s terminology is based upon the excellent book &lt;a href="http://xunitpatterns.com/"&gt;xUnit
Test Patterns&lt;/a&gt;, and a Fixture instance pretty much corresponds to the concept of
a &lt;a href="http://xunitpatterns.com/test%20fixture%20-%20xUnit.html"&gt;Fixture&lt;/a&gt;.
This means that freezing an instance simply means that a particular instance is constant
throughout that particular fixture. Every time we ask for an instance of that class,
we get back the same frozen instance.
&lt;/p&gt;
&lt;p&gt;
In DI Container terminology, we just changed the Basket type’s lifetime behavior from
Transient to Singleton.
&lt;/p&gt;
&lt;p&gt;
For reference, here’s the BasketPresenter class we’re testing:
&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 BasketPresenter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 Basket\cf0  basket;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IPizzaMap\cf0  map;\par ??\par ??    \cf1 public\cf0  BasketPresenter(\cf4 Basket\cf0  basket, \cf4 IPizzaMap\cf0  map)\par ??    \{\par ??        \cf1 if\cf0  (basket == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "basket"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (map == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "map"\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .basket = basket;\par ??        \cf1 this\cf0 .map = map;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Add(\cf4 PizzaPresenter\cf0  presenter)\par ??    \{\par ??        \cf1 this\cf0 .map.Pipe(presenter, \cf1 this\cf0 .basket.Add);\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;BasketPresenter&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;Basket&lt;/span&gt; basket;&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;IPizzaMap&lt;/span&gt; map;&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; BasketPresenter(&lt;span style="color: #2b91af"&gt;Basket&lt;/span&gt; basket, &lt;span style="color: #2b91af"&gt;IPizzaMap&lt;/span&gt; map)&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; (basket
== &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;"basket"&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; (map
== &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;"map"&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;.basket
= basket;&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;.map
= map;&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; Add(&lt;span style="color: #2b91af"&gt;PizzaPresenter&lt;/span&gt; presenter)&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;.map.Pipe(presenter, &lt;span style="color: blue"&gt;this&lt;/span&gt;.basket.Add);&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;
If you are wondering about why this is interesting at all, and why we don’t just pass
in a Basket through the BasketPresenter’s constructor, it’s because we are using AutoFixture
as a &lt;a href="http://blog.ploeh.dk/2009/02/13/SUTFactory.aspx"&gt;SUT Factory&lt;/a&gt;. We
want to be able to refactor BasketPresenter (and in this case particularly its constructor)
without breaking a lot of existing tests. The level of indirection provided by AutoFixture
gives us just that ability because we never directly invoke the constructor.
&lt;/p&gt;
&lt;p&gt;
Coming up: &lt;a href="http://blog.ploeh.dk/2010/03/27/FreezingMocks.aspx"&gt;more fun with
the Freeze concept&lt;/a&gt;!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=0b36f631-086d-4d79-a1ad-5153716987b0" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,0b36f631-086d-4d79-a1ad-5153716987b0.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=23c49b8a-f9e3-4012-8172-d7cf4584341d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,23c49b8a-f9e3-4012-8172-d7cf4584341d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,23c49b8a-f9e3-4012-8172-d7cf4584341d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=23c49b8a-f9e3-4012-8172-d7cf4584341d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of the important points of <a href="http://autofixture.codeplex.com/">AutoFixture</a> is
to hide away all the boring details that you don’t care about when you are writing
a unit test, but that the compiler seems to insist upon. One of these details is how
you create a new instance of your <a href="http://xunitpatterns.com/SUT.html">SUT</a>.
</p>
        <p>
Every time you create an instance of your SUT using its constructor, you make it more
difficult to refactor that constructor. This is particularly true when it comes to
Constructor Injection because you often need to define a <a href="http://xunitpatterns.com/Test%20Double.html">Test
Double</a> in each unit test, but even for primitive types, it’s more maintenance-friendly
to use a <a href="http://blog.ploeh.dk/2009/02/13/SUTFactory.aspx">SUT Factory</a>.
</p>
        <p>
AutoFixture is a SUT Factory, so we can use it to create instances of our SUTs. However,
how do we correlate constructor parameters with variables in the test when we will
not use the constructor directly?
</p>
        <p>
This is where the Freeze method comes in handy, but let’s first examine how to do
it with the core API methods <a href="http://blog.ploeh.dk/2009/04/02/CreatingStringsWithAutoFixture.aspx">CreateAnonymous</a> and <a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx">Register</a>.
</p>
        <p>
Imagine that we want to write a unit test for a Pizza class that takes a name in its
constructor and exposes that name as a property. We can write this 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  NameIsCorrect()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??\par ??    \cf4 var\cf0  expectedName = fixture.CreateAnonymous(\cf6 "Name"\cf0 );\par ??    fixture.Register(expectedName);\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 Pizza\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 string\cf0  result = sut.Name;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual(expectedName, result, \cf6 "Name"\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> NameIsCorrect()</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"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> expectedName
= fixture.CreateAnonymous(<span style="color: #a31515">"Name"</span>);</pre>
          <pre style="margin: 0px">    fixture.Register(expectedName);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Pizza</span>&gt;();</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.Name;</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual(expectedName,
result, <span style="color: #a31515">"Name"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The important lines are these two:
</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;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  expectedName = fixture.CreateAnonymous(\cf4 "Name"\cf0 );\par ??fixture.Register(expectedName);}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> expectedName
= fixture.CreateAnonymous(<span style="color: #a31515">"Name"</span>);</pre>
          <pre style="margin: 0px">fixture.Register(expectedName);</pre>
        </div>
        <p>
What’s going on here is that we create a new string, and then we subsequently Register
this string so that <em>every time</em> the fixture instance is asked to create a
string, it will return this particular string. This also means that when we ask AutoFixture
to create an instance of Pizza, it will use that string as the constructor parameter.
</p>
        <p>
It turned out that we used this coding idiom so much that we decided to encapsulate
it in a convenience method. After some debate we arrived at the name Freeze, because
we essentially freeze a single anonymous variable in the fixture, bypassing the default
algorithm for creating new instances. Incidentally, this is one of very few methods
in AutoFixture that breaks CQS, but although that bugs me a little, the Freeze concept
has turned out to be so powerful that I live with it.
</p>
        <p>
Here is the same test rewritten to use the Freeze 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  NameIsCorrect_Freeze()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf4 var\cf0  expectedName = fixture.Freeze(\cf6 "Name"\cf0 );\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&lt;\cf3 Pizza\cf0 &gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 string\cf0  result = sut.Name;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual(expectedName, result, \cf6 "Name"\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> NameIsCorrect_Freeze()</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> expectedName
= fixture.Freeze(<span style="color: #a31515">"Name"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">Pizza</span>&gt;();</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.Name;</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Verify outcome</span></pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.AreEqual(expectedName,
result, <span style="color: #a31515">"Name"</span>);</pre>
          <pre style="margin: 0px">    <span style="color: green">//
Teardown</span></pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this example, we only save a single line of code, but apart from that, the test
also becomes a little more communicative because it explicitly calls out that this
particular string is frozen.
</p>
        <p>
However, this is still a pretty lame example, but while I intend to follow up with
a more complex example, I wanted to introduce the concept gently.
</p>
        <p>
For completeness sake, here’s the Pizza 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 Pizza\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 string\cf0  name;\par ??\par ??    \cf1 public\cf0  Pizza(\cf1 string\cf0  name)\par ??    \{\par ??        \cf1 if\cf0  (name == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "name"\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .name = name;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 string\cf0  Name\par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .name; \}\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">Pizza</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">string</span> name;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> Pizza(<span style="color: blue">string</span> name)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (name
== <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">"name"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.name
= name;</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> Name</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>.name;
}</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
As you can see, the test simply verifies that the constructor parameter is echoed
by the Name property, and the Freeze method makes this more explicit while we still
enjoy the indirection of not invoking the constructor directly.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=23c49b8a-f9e3-4012-8172-d7cf4584341d" />
      </body>
      <title>AutoFixture Freeze</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,23c49b8a-f9e3-4012-8172-d7cf4584341d.aspx</guid>
      <link>http://blog.ploeh.dk/2010/03/17/AutoFixtureFreeze.aspx</link>
      <pubDate>Wed, 17 Mar 2010 21:54:53 GMT</pubDate>
      <description>&lt;p&gt;
One of the important points of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; is
to hide away all the boring details that you don’t care about when you are writing
a unit test, but that the compiler seems to insist upon. One of these details is how
you create a new instance of your &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Every time you create an instance of your SUT using its constructor, you make it more
difficult to refactor that constructor. This is particularly true when it comes to
Constructor Injection because you often need to define a &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test
Double&lt;/a&gt; in each unit test, but even for primitive types, it’s more maintenance-friendly
to use 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;
AutoFixture is a SUT Factory, so we can use it to create instances of our SUTs. However,
how do we correlate constructor parameters with variables in the test when we will
not use the constructor directly?
&lt;/p&gt;
&lt;p&gt;
This is where the Freeze method comes in handy, but let’s first examine how to do
it with the core API methods &lt;a href="http://blog.ploeh.dk/2009/04/02/CreatingStringsWithAutoFixture.aspx"&gt;CreateAnonymous&lt;/a&gt; and &lt;a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx"&gt;Register&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Imagine that we want to write a unit test for a Pizza class that takes a name in its
constructor and exposes that name as a property. We can write this 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  NameIsCorrect()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??\par ??    \cf4 var\cf0  expectedName = fixture.CreateAnonymous(\cf6 "Name"\cf0 );\par ??    fixture.Register(expectedName);\par ??\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 Pizza\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 string\cf0  result = sut.Name;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual(expectedName, result, \cf6 "Name"\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; NameIsCorrect()&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;&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; expectedName
= fixture.CreateAnonymous(&lt;span style="color: #a31515"&gt;"Name"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; fixture.Register(expectedName);&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.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;Pizza&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;string&lt;/span&gt; result
= sut.Name;&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(expectedName,
result, &lt;span style="color: #a31515"&gt;"Name"&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 important lines are these two:
&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;\red163\green21\blue21;}??\fs20 \cf1 var\cf0  expectedName = fixture.CreateAnonymous(\cf4 "Name"\cf0 );\par ??fixture.Register(expectedName);}
--&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; expectedName
= fixture.CreateAnonymous(&lt;span style="color: #a31515"&gt;"Name"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.Register(expectedName);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What’s going on here is that we create a new string, and then we subsequently Register
this string so that &lt;em&gt;every time&lt;/em&gt; the fixture instance is asked to create a
string, it will return this particular string. This also means that when we ask AutoFixture
to create an instance of Pizza, it will use that string as the constructor parameter.
&lt;/p&gt;
&lt;p&gt;
It turned out that we used this coding idiom so much that we decided to encapsulate
it in a convenience method. After some debate we arrived at the name Freeze, because
we essentially freeze a single anonymous variable in the fixture, bypassing the default
algorithm for creating new instances. Incidentally, this is one of very few methods
in AutoFixture that breaks CQS, but although that bugs me a little, the Freeze concept
has turned out to be so powerful that I live with it.
&lt;/p&gt;
&lt;p&gt;
Here is the same test rewritten to use the Freeze 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  NameIsCorrect_Freeze()\par ??\{\par ??    \cf5 // Fixture setup\par ??\cf0     \cf4 var\cf0  fixture = \cf4 new\cf0  \cf3 Fixture\cf0 ();\par ??    \cf4 var\cf0  expectedName = fixture.Freeze(\cf6 "Name"\cf0 );\par ??    \cf4 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf3 Pizza\cf0 &amp;gt;();\par ??    \cf5 // Exercise system\par ??\cf0     \cf4 string\cf0  result = sut.Name;\par ??    \cf5 // Verify outcome\par ??\cf0     \cf3 Assert\cf0 .AreEqual(expectedName, result, \cf6 "Name"\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; NameIsCorrect_Freeze()&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; expectedName
= fixture.Freeze(&lt;span style="color: #a31515"&gt;"Name"&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;Pizza&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;string&lt;/span&gt; result
= sut.Name;&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(expectedName,
result, &lt;span style="color: #a31515"&gt;"Name"&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 example, we only save a single line of code, but apart from that, the test
also becomes a little more communicative because it explicitly calls out that this
particular string is frozen.
&lt;/p&gt;
&lt;p&gt;
However, this is still a pretty lame example, but while I intend to follow up with
a more complex example, I wanted to introduce the concept gently.
&lt;/p&gt;
&lt;p&gt;
For completeness sake, here’s the Pizza 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 Pizza\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf1 string\cf0  name;\par ??\par ??    \cf1 public\cf0  Pizza(\cf1 string\cf0  name)\par ??    \{\par ??        \cf1 if\cf0  (name == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "name"\cf0 );\par ??        \}\par ??\par ??        \cf1 this\cf0 .name = name;\par ??    \}\par ??\par ??    \cf1 public\cf0  \cf1 string\cf0  Name\par ??    \{\par ??        \cf1 get\cf0  \{ \cf1 return\cf0  \cf1 this\cf0 .name; \}\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;Pizza&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;string&lt;/span&gt; name;&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; Pizza(&lt;span style="color: blue"&gt;string&lt;/span&gt; name)&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; (name
== &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;"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; }&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;.name
= name;&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; Name&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;.name;
}&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;
As you can see, the test simply verifies that the constructor parameter is echoed
by the Name property, and the Freeze method makes this more explicit while we still
enjoy the indirection of not invoking the constructor directly.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=23c49b8a-f9e3-4012-8172-d7cf4584341d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,23c49b8a-f9e3-4012-8172-d7cf4584341d.aspx</comments>
      <category>AutoFixture</category>
      <category>Unit Testing</category>
    </item>
    <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>20</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>2</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>7</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>5</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>
  </channel>
</rss>