<?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 - Software Design</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=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=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=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=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=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=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When I talk with people about TDD and unit testing, the discussion often moves into
the area of Testability – that is, the software's susceptibility to unit testing.
A couple of years back, <a href="http://weblogs.asp.net/rosherove/default.aspx">Roy</a> even
discussed the seemingly <a href="http://weblogs.asp.net/rosherove/archive/2007/02/25/why-you-should-think-about-ootp-object-oriented-testable-programming.aspx">opposable
forces of Object-Oriented Design and Testability</a>.
</p>
        <p>
Lately, it has been occurring to me that there really isn't any conflict. Encapsulation
is important because it manifests expert knowledge so that other developers can effectively
leverage that knowledge, and it does so in a way that minimizes misuse.
</p>
        <p>
However, too much encapsulation goes against the Open/Closed Principle (that states
that objects should be open for extension, but closed for modification). From a Testability
perspective, the Open/Closed Principle pulls object-oriented design in the desired
direction. Equivalently, done correctly, making your API Testable is simply opening
it up for extensibility.
</p>
        <p>
As an example, consider a simple <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">WPF
ViewModel</a> class called MainWindowViewModel. This class has an <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx">ICommand</a> property
that, when invoked, should show a message box. Showing a message box is good example
of breaking testability, because if the <a href="http://xunitpatterns.com/SUT.html">SUT</a> were
to show a message box, it would be very hard to automatically verify and we wouldn't
have fully automated tests.
</p>
        <p>
For this reason, we need to introduce an abstraction that basically models an action
with a string as input. <a href="http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx">Although
we could define an interface for that, an Action&lt;string&gt; fits the bill perfectly</a>.
</p>
        <p>
To enable that feature, I decide to use Constructor Injection to inject that abstraction
into the MainWindowViewModel class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  MainWindowViewModel(\cf4 Action\cf0 &lt;\cf1 string\cf0 &gt; notify)\par ??\{\par ??    \cf1 this\cf0 .ButtonCommand = \cf1 new\cf0  \cf4 RelayCommand\cf0 (p =&gt; \par ??    \{ notify(\cf5 "Button was clicked!"\cf0 ); \});\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> MainWindowViewModel(<span style="color: #2b91af">Action</span>&lt;<span style="color: blue">string</span>&gt;
notify)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.ButtonCommand
= <span style="color: blue">new</span><span style="color: #2b91af">RelayCommand</span>(p
=&gt; </pre>
          <pre style="margin: 0px">    { notify(<span style="color: #a31515">"Button
was clicked!"</span>); });</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
When I recently did that at a public talk I gave, one member of the audience initially
reacted by assuming that I was now introducing test-specific code into my SUT, but
that's not the case.
</p>
        <p>
What I'm really doing here is opening the MainWindowViewModel class for extensibility.
It can still be used with message boxes:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  vm = \cf1 new\cf0  \cf4 MainWindowViewModel\cf0 (s =&gt; \cf4 MessageBox\cf0 .Show(s));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> vm
= <span style="color: blue">new</span><span style="color: #2b91af">MainWindowViewModel</span>(s
=&gt; <span style="color: #2b91af">MessageBox</span>.Show(s));</pre>
        </div>
        <p>
but now we also have the option of notifying by sending off an email; writing to a
database; or whatever else we can think of.
</p>
        <p>
It just so happens that one of the things we can do instead of showing a message box,
is unit testing by passing in a <a href="http://xunitpatterns.com/Test%20Double.html">Test
Double</a>.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  mockNotify = \par ??    \cf5 MockRepository\cf0 .GenerateMock&lt;\cf5 Action\cf0 &lt;\cf3 string\cf0 &gt;&gt;();\par ??mockNotify.Expect(a =&gt; a(\cf6 "Button was clicked!"\cf0 ));\par ??\par ??\cf3 var\cf0  sut = \cf3 new\cf0  \cf5 MainWindowViewModel\cf0 (mockNotify);\par ??\cf1 // Exercise system\par ??\cf0 sut.ButtonCommand.Execute(\cf3 new\cf0  \cf3 object\cf0 ());\par ??\cf1 // Verify outcome\par ??\cf0 mockNotify.VerifyAllExpectations();\par ??\cf1 // Teardown}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: green">//
Fixture setup</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> mockNotify
= </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">Action</span>&lt;<span style="color: blue">string</span>&gt;&gt;();</pre>
          <pre style="margin: 0px">mockNotify.Expect(a =&gt; a(<span style="color: #a31515">"Button
was clicked!"</span>));</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MainWindowViewModel</span>(mockNotify);</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Exercise system</span>
          </pre>
          <pre style="margin: 0px">sut.ButtonCommand.Execute(<span style="color: blue">new</span><span style="color: blue">object</span>());</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Verify outcome</span>
          </pre>
          <pre style="margin: 0px">mockNotify.VerifyAllExpectations();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Teardown</span>
          </pre>
        </div>
        <p>
Once again, TDD has lead to better design. In this case it prompted me to open the
class for extensibility. There really isn't a need for Testability as a specific concept;
the Open/Closed Principle should be enough to drive us in the right direction.
</p>
        <p>
Pragmatically, that's not the case, so we use TDD to drive us towards the Open/Closed
Principle, but I think it's important to note that we are not only doing this to enable
testing: We are creating a better and more flexible API at the same time.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c" />
      </body>
      <title>Testability Is Really The Open/Closed Principle</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</guid>
      <link>http://blog.ploeh.dk/2009/06/05/TestabilityIsReallyTheOpenClosedPrinciple.aspx</link>
      <pubDate>Fri, 05 Jun 2009 07:56:19 GMT</pubDate>
      <description>&lt;p&gt;
When I talk with people about TDD and unit testing, the discussion often moves into
the area of Testability – that is, the software's susceptibility to unit testing.
A couple of years back, &lt;a href="http://weblogs.asp.net/rosherove/default.aspx"&gt;Roy&lt;/a&gt; even
discussed the seemingly &lt;a href="http://weblogs.asp.net/rosherove/archive/2007/02/25/why-you-should-think-about-ootp-object-oriented-testable-programming.aspx"&gt;opposable
forces of Object-Oriented Design and Testability&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
Lately, it has been occurring to me that there really isn't any conflict. Encapsulation
is important because it manifests expert knowledge so that other developers can effectively
leverage that knowledge, and it does so in a way that minimizes misuse.
&lt;/p&gt;
&lt;p&gt;
However, too much encapsulation goes against the Open/Closed Principle (that states
that objects should be open for extension, but closed for modification). From a Testability
perspective, the Open/Closed Principle pulls object-oriented design in the desired
direction. Equivalently, done correctly, making your API Testable is simply opening
it up for extensibility.
&lt;/p&gt;
&lt;p&gt;
As an example, consider a simple &lt;a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx"&gt;WPF
ViewModel&lt;/a&gt; class called MainWindowViewModel. This class has an &lt;a href="http://msdn.microsoft.com/en-us/library/system.windows.input.icommand.aspx"&gt;ICommand&lt;/a&gt; property
that, when invoked, should show a message box. Showing a message box is good example
of breaking testability, because if the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt; were
to show a message box, it would be very hard to automatically verify and we wouldn't
have fully automated tests.
&lt;/p&gt;
&lt;p&gt;
For this reason, we need to introduce an abstraction that basically models an action
with a string as input. &lt;a href="http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx"&gt;Although
we could define an interface for that, an Action&amp;lt;string&amp;gt; fits the bill perfectly&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
To enable that feature, I decide to use Constructor Injection to inject that abstraction
into the MainWindowViewModel class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  MainWindowViewModel(\cf4 Action\cf0 &amp;lt;\cf1 string\cf0 &amp;gt; notify)\par ??\{\par ??    \cf1 this\cf0 .ButtonCommand = \cf1 new\cf0  \cf4 RelayCommand\cf0 (p =&amp;gt; \par ??    \{ notify(\cf5 "Button was clicked!"\cf0 ); \});\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; MainWindowViewModel(&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;
notify)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ButtonCommand
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;RelayCommand&lt;/span&gt;(p
=&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; { notify(&lt;span style="color: #a31515"&gt;"Button
was clicked!"&lt;/span&gt;); });&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
When I recently did that at a public talk I gave, one member of the audience initially
reacted by assuming that I was now introducing test-specific code into my SUT, but
that's not the case.
&lt;/p&gt;
&lt;p&gt;
What I'm really doing here is opening the MainWindowViewModel class for extensibility.
It can still be used with message boxes:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 var\cf0  vm = \cf1 new\cf0  \cf4 MainWindowViewModel\cf0 (s =&amp;gt; \cf4 MessageBox\cf0 .Show(s));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; vm
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MainWindowViewModel&lt;/span&gt;(s
=&amp;gt; &lt;span style="color: #2b91af"&gt;MessageBox&lt;/span&gt;.Show(s));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
but now we also have the option of notifying by sending off an email; writing to a
database; or whatever else we can think of.
&lt;/p&gt;
&lt;p&gt;
It just so happens that one of the things we can do instead of showing a message box,
is unit testing by passing in a &lt;a href="http://xunitpatterns.com/Test%20Double.html"&gt;Test
Double&lt;/a&gt;.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  mockNotify = \par ??    \cf5 MockRepository\cf0 .GenerateMock&amp;lt;\cf5 Action\cf0 &amp;lt;\cf3 string\cf0 &amp;gt;&amp;gt;();\par ??mockNotify.Expect(a =&amp;gt; a(\cf6 "Button was clicked!"\cf0 ));\par ??\par ??\cf3 var\cf0  sut = \cf3 new\cf0  \cf5 MainWindowViewModel\cf0 (mockNotify);\par ??\cf1 // Exercise system\par ??\cf0 sut.ButtonCommand.Execute(\cf3 new\cf0  \cf3 object\cf0 ());\par ??\cf1 // Verify outcome\par ??\cf0 mockNotify.VerifyAllExpectations();\par ??\cf1 // Teardown}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; mockNotify
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;Action&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mockNotify.Expect(a =&amp;gt; a(&lt;span style="color: #a31515"&gt;"Button
was clicked!"&lt;/span&gt;));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MainWindowViewModel&lt;/span&gt;(mockNotify);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.ButtonCommand.Execute(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: blue"&gt;object&lt;/span&gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mockNotify.VerifyAllExpectations();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Once again, TDD has lead to better design. In this case it prompted me to open the
class for extensibility. There really isn't a need for Testability as a specific concept;
the Open/Closed Principle should be enough to drive us in the right direction.
&lt;/p&gt;
&lt;p&gt;
Pragmatically, that's not the case, so we use TDD to drive us towards the Open/Closed
Principle, but I think it's important to note that we are not only doing this to enable
testing: We are creating a better and more flexible API at the same time.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,3cdd18ec-a1a3-4572-9a5d-4b914b0fbd7c.aspx</comments>
      <category>Software Design</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
This is really nothing new, but I don't think I've explicitly stated this before:
It makes a lot of sense to view delegates as anonymous one-method interfaces.
</p>
        <p>
Many people liken delegates to function pointers. While that's probably correct (I
wouldn't really know), it's not a very object-oriented view to take – at least not
when we are dealing with managed code. To me, it makes more sense to view delegates
as anonymous one-method interfaces.
</p>
        <p>
Lets consider a simple example. As always, we have the ubiquitous MyClass with its
DoStuff method. In this example, DoStuff takes as input an abstraction that takes
a string as input and returns an integer – let's imagine that this is some kind of
Strategy (notice the capital <em>S</em> – I'm talking about the design pattern, here).
</p>
        <p>
In traditional object-oriented design, we could solve this by introducing the IMyInterface
type:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IMyInterface\par ??\cf0 \{\par ??    \cf1 int\cf0  DoIt(\cf1 string\cf0  message);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IMyInterface</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">int</span> DoIt(<span style="color: blue">string</span> message);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The implementation of DoStuff is simply:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 IMyInterface\cf0  strategy)\par ??\{\par ??    \cf1 return\cf0  strategy.DoIt(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">string</span> DoStuff(<span style="color: #2b91af">IMyInterface</span> strategy)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> strategy.DoIt(<span style="color: #a31515">"Ploeh"</span>).ToString();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Hardly rocket science…
</p>
        <p>
However, defining a completely new interface just to do this is not really necessary,
since we could just as well have implemented DoStuff with a Func&lt;string, int&gt;:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 Func\cf0 &lt;\cf1 string\cf0 , \cf1 int\cf0 &gt; strategy)\par ??\{\par ??    \cf1 return\cf0  strategy(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">string</span> DoStuff(<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;
strategy)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> strategy(<span style="color: #a31515">"Ploeh"</span>).ToString();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This not only frees us from defining a new interface, but also from implementing that
interface to use the DoStuff method. Instead, we can simply pass a lambda expression:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 string\cf0  result = sut.DoStuff(s =&gt; s.Count());}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">string</span> result
= sut.DoStuff(s =&gt; s.Count());</pre>
        </div>
        <p>
What's most amazing is that <a href="http://ayende.com/projects/rhino-mocks.aspx">RhinoMocks</a> understands
and treats delegates just like other abstract types, so that we can write the following
to treat it as a mock:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue0;\red0\green0\blue255;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 Func\cf0 &lt;\cf5 string\cf0 , \cf5 int\cf0 &gt; mock =\par ??    \cf3 MockRepository\cf0 .GenerateMock&lt;\cf3 Func\cf0 &lt;\cf5 string\cf0 , \cf5 int\cf0 &gt;&gt;();\par ??mock.Expect(f =&gt; f(\cf6 "Ploeh"\cf0 )).Return(42);\par ??\cf5 var\cf0  sut = \cf5 new\cf0  \cf3 MyClass\cf0 ();\par ??\cf1 // Exercise system\par ??\cf5 string\cf0  result = sut.DoStuff(mock);\par ??\cf1 // Verify outcome\par ??\cf0 mock.VerifyAllExpectations();\par ??\cf1 // Teardown}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: green">//
Fixture setup</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;
mock =</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">MockRepository</span>.GenerateMock&lt;<span style="color: #2b91af">Func</span>&lt;<span style="color: blue">string</span>, <span style="color: blue">int</span>&gt;&gt;();</pre>
          <pre style="margin: 0px">mock.Expect(f =&gt; f(<span style="color: #a31515">"Ploeh"</span>)).Return(42);</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">MyClass</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Exercise system</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">string</span> result
= sut.DoStuff(mock);</pre>
          <pre style="margin: 0px">
            <span style="color: green">// Verify
outcome</span>
          </pre>
          <pre style="margin: 0px">mock.VerifyAllExpectations();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Teardown</span>
          </pre>
        </div>
        <p>
Whenever possible, I prefer to model my APIs with delegates instead of one-method
interfaces, since it gives me greater flexibility and less infrastructure code.
</p>
        <p>
Obviously, this technique only works as long as you only need to abstract a single
method. As soon as your abstraction needs a second method, you will need to introduce
a proper interface or, preferably, an abstract base class.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b" />
      </body>
      <title>Delegates Are Anonymous Interfaces</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/28/DelegatesAreAnonymousInterfaces.aspx</link>
      <pubDate>Thu, 28 May 2009 20:19:04 GMT</pubDate>
      <description>&lt;p&gt;
This is really nothing new, but I don't think I've explicitly stated this before:
It makes a lot of sense to view delegates as anonymous one-method interfaces.
&lt;/p&gt;
&lt;p&gt;
Many people liken delegates to function pointers. While that's probably correct (I
wouldn't really know), it's not a very object-oriented view to take – at least not
when we are dealing with managed code. To me, it makes more sense to view delegates
as anonymous one-method interfaces.
&lt;/p&gt;
&lt;p&gt;
Lets consider a simple example. As always, we have the ubiquitous MyClass with its
DoStuff method. In this example, DoStuff takes as input an abstraction that takes
a string as input and returns an integer – let's imagine that this is some kind of
Strategy (notice the capital &lt;em&gt;S&lt;/em&gt; – I'm talking about the design pattern, here).
&lt;/p&gt;
&lt;p&gt;
In traditional object-oriented design, we could solve this by introducing the IMyInterface
type:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IMyInterface\par ??\cf0 \{\par ??    \cf1 int\cf0  DoIt(\cf1 string\cf0  message);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;interface&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;int&lt;/span&gt; DoIt(&lt;span style="color: blue"&gt;string&lt;/span&gt; message);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The implementation of DoStuff is simply:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 IMyInterface\cf0  strategy)\par ??\{\par ??    \cf1 return\cf0  strategy.DoIt(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; DoStuff(&lt;span style="color: #2b91af"&gt;IMyInterface&lt;/span&gt; strategy)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; strategy.DoIt(&lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;).ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Hardly rocket science…
&lt;/p&gt;
&lt;p&gt;
However, defining a completely new interface just to do this is not really necessary,
since we could just as well have implemented DoStuff with a Func&amp;lt;string, int&amp;gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 string\cf0  DoStuff(\cf4 Func\cf0 &amp;lt;\cf1 string\cf0 , \cf1 int\cf0 &amp;gt; strategy)\par ??\{\par ??    \cf1 return\cf0  strategy(\cf5 "Ploeh"\cf0 ).ToString();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; DoStuff(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;
strategy)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; strategy(&lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;).ToString();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This not only frees us from defining a new interface, but also from implementing that
interface to use the DoStuff method. Instead, we can simply pass a lambda expression:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 string\cf0  result = sut.DoStuff(s =&amp;gt; s.Count());}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;string&lt;/span&gt; result
= sut.DoStuff(s =&amp;gt; s.Count());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What's most amazing is that &lt;a href="http://ayende.com/projects/rhino-mocks.aspx"&gt;RhinoMocks&lt;/a&gt; understands
and treats delegates just like other abstract types, so that we can write the following
to treat it as a mock:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue0;\red0\green0\blue255;\red163\green21\blue21;}??\fs20 \cf1 // Fixture setup\par ??\cf3 Func\cf0 &amp;lt;\cf5 string\cf0 , \cf5 int\cf0 &amp;gt; mock =\par ??    \cf3 MockRepository\cf0 .GenerateMock&amp;lt;\cf3 Func\cf0 &amp;lt;\cf5 string\cf0 , \cf5 int\cf0 &amp;gt;&amp;gt;();\par ??mock.Expect(f =&amp;gt; f(\cf6 "Ploeh"\cf0 )).Return(42);\par ??\cf5 var\cf0  sut = \cf5 new\cf0  \cf3 MyClass\cf0 ();\par ??\cf1 // Exercise system\par ??\cf5 string\cf0  result = sut.DoStuff(mock);\par ??\cf1 // Verify outcome\par ??\cf0 mock.VerifyAllExpectations();\par ??\cf1 // Teardown}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;
mock =&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MockRepository&lt;/span&gt;.GenerateMock&amp;lt;&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;, &lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mock.Expect(f =&amp;gt; f(&lt;span style="color: #a31515"&gt;"Ploeh"&lt;/span&gt;)).Return(42);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;MyClass&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;string&lt;/span&gt; result
= sut.DoStuff(mock);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;// Verify
outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;mock.VerifyAllExpectations();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Whenever possible, I prefer to model my APIs with delegates instead of one-method
interfaces, since it gives me greater flexibility and less infrastructure code.
&lt;/p&gt;
&lt;p&gt;
Obviously, this technique only works as long as you only need to abstract a single
method. As soon as your abstraction needs a second method, you will need to introduce
a proper interface or, preferably, an abstract base class.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=9e284836-e8b5-4f8a-afd5-e4f1fa3a838b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,9e284836-e8b5-4f8a-afd5-e4f1fa3a838b.aspx</comments>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=b828bf52-1b68-4a15-814f-546b52f7bea1</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,b828bf52-1b68-4a15-814f-546b52f7bea1.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,b828bf52-1b68-4a15-814f-546b52f7bea1.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=b828bf52-1b68-4a15-814f-546b52f7bea1</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.udidahan.com/?blog=true">Udi</a> recently posted an <a href="http://www.udidahan.com/2009/05/03/projects-assemblies-and-namespaces-oh-my/">article
on managing loose coupling</a> in Visual Studio. While I completely agree, this is
a topic that deserves more detailed treatment. In particular, I'd like to expand on
this statement: 
</p>
        <p>
"In fact, each component could theoretically have its own solution" 
</p>
        <p>
This is really the crux of the matter, although in practical terms, you'd typically
need at least a couple of projects per component. In special cases, a component may
truly be a stand-alone component, requiring no other dependencies than what is already
in the BCL (in fact, <a href="http://autofixture.codeplex.com/">AutoFixture</a> is
just such a component), but most components of more complex software have dependencies. 
</p>
        <p>
Even when you are programming against interfaces (which you should be), these interfaces
will normally be defined in other projects. 
</p>
        <p>
          <a href="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ManagingLooselyCoupledProject_12017/PragmaticMinimalSolution_2.png">
            <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="PragmaticMinimalSolution" border="0" alt="PragmaticMinimalSolution" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ManagingLooselyCoupledProject_12017/PragmaticMinimalSolution_thumb.png" width="640" height="364" />
          </a>
        </p>
        <p>
A component may even use multiple interfaces, since it may be implementing some, but
consuming others, and these interfaces may be defined in different projects. This
is particularly the case with Adapters. 
</p>
        <p>
Finally, you should have at least one unit test project that targets your component. 
</p>
        <p>
In essence, while the exact number of projects you need will vary, it should stay
small. In the figure above, we end up with five projects, but there's also quite a
few abstractions being pulled in. 
</p>
        <p>
As a rule of thumb I'd say that if you <em>can't</em> create an .sln file that contains
less than ten projects to work on any component, you should seriously consider your
decoupling strategy. 
</p>
        <p>
You may <em>choose</em> to work with more than ten projects in a solution, but it
should always be possible to create a solution to work with a single component, and
it should drag only few dependencies along.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b828bf52-1b68-4a15-814f-546b52f7bea1" />
      </body>
      <title>Managing Loosely Coupled Projects</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,b828bf52-1b68-4a15-814f-546b52f7bea1.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/05/ManagingLooselyCoupledProjects.aspx</link>
      <pubDate>Tue, 05 May 2009 18:54:11 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://www.udidahan.com/?blog=true"&gt;Udi&lt;/a&gt; recently posted an &lt;a href="http://www.udidahan.com/2009/05/03/projects-assemblies-and-namespaces-oh-my/"&gt;article
on managing loose coupling&lt;/a&gt; in Visual Studio. While I completely agree, this is
a topic that deserves more detailed treatment. In particular, I'd like to expand on
this statement: 
&lt;p&gt;
"In fact, each component could theoretically have its own solution" 
&lt;p&gt;
This is really the crux of the matter, although in practical terms, you'd typically
need at least a couple of projects per component. In special cases, a component may
truly be a stand-alone component, requiring no other dependencies than what is already
in the BCL (in fact, &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt; is
just such a component), but most components of more complex software have dependencies. 
&lt;p&gt;
Even when you are programming against interfaces (which you should be), these interfaces
will normally be defined in other projects. 
&lt;p&gt;
&lt;a href="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ManagingLooselyCoupledProject_12017/PragmaticMinimalSolution_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="PragmaticMinimalSolution" border="0" alt="PragmaticMinimalSolution" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ManagingLooselyCoupledProject_12017/PragmaticMinimalSolution_thumb.png" width="640" height="364"&gt;&lt;/a&gt; 
&lt;p&gt;
A component may even use multiple interfaces, since it may be implementing some, but
consuming others, and these interfaces may be defined in different projects. This
is particularly the case with Adapters. 
&lt;p&gt;
Finally, you should have at least one unit test project that targets your component. 
&lt;p&gt;
In essence, while the exact number of projects you need will vary, it should stay
small. In the figure above, we end up with five projects, but there's also quite a
few abstractions being pulled in. 
&lt;p&gt;
As a rule of thumb I'd say that if you &lt;em&gt;can't&lt;/em&gt; create an .sln file that contains
less than ten projects to work on any component, you should seriously consider your
decoupling strategy. 
&lt;p&gt;
You may &lt;em&gt;choose&lt;/em&gt; to work with more than ten projects in a solution, but it
should always be possible to create a solution to work with a single component, and
it should drag only few dependencies along.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b828bf52-1b68-4a15-814f-546b52f7bea1" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,b828bf52-1b68-4a15-814f-546b52f7bea1.aspx</comments>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=91aa4494-6b37-4ac9-b268-11493706669f</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,91aa4494-6b37-4ac9-b268-11493706669f.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,91aa4494-6b37-4ac9-b268-11493706669f.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=91aa4494-6b37-4ac9-b268-11493706669f</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
As a response to my description of <a href="http://blog.ploeh.dk/2009/03/24/HowAutoFixtureCreatesObjects.aspx">how
AutoFixture creates objects</a>, Klaus asked:
</p>
        <p>
“[What] if the constructor of ComplexChild imposes some kind of restriction on its
parameter? If, for example, instead of the "name" parameter, it would take a "phoneNumber"
parameter (as a string), and do some format checking?”
</p>
        <p>
Now that we have covered some of the basic features of <a href="http://autofixture.codeplex.com/">AutoFixture</a>,
it’s time to properly answer this excellent question.
</p>
        <p>
For simplicity’s sake, let’s assume that the phone number in question is a Danish
phone number: This is pretty good for example code, since a Danish phone number is
essentially just an 8-digit number. It can have white space and an optional country
code (+45), but strip that away, and it’s just an 8-digit number. However, there are
exceptions, since the emergency number is 112 (equivalent to the American 911), and
other 3-digit special numbers exist as well.
</p>
        <p>
With that in mind, let’s look at a simple Contact class that contains a contact’s
name and Danish phone number. The constructor might look like this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  Contact(\cf1 string\cf0  name, \cf1 string\cf0  phoneNumber)\par ??\{\par ??    \cf1 this\cf0 .Name = name;\par ??    \cf1 this\cf0 .PhoneNumber = \par ??        \cf4 Contact\cf0 .ParsePhoneNumber(phoneNumber);\par ??\}}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> Contact(<span style="color: blue">string</span> name, <span style="color: blue">string</span> phoneNumber)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.Name
= name;</pre>
          <pre style="margin: 0px">    <span style="color: blue">this</span>.PhoneNumber
= </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Contact</span>.ParsePhoneNumber(phoneNumber);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The static ParsePhoneNumber method strips away white space and optional country code
and parses the normalized string to a number. This fits the scenario laid out in Klaus’
question.
</p>
        <p>
So what happens when we ask AutoFixture to create an instance of Contact? It will
Reflect over Contact’s constructor and create two new anonymous string instances –
one for name, and one for phoneNumber. As <a href="http://blog.ploeh.dk/2009/04/02/CreatingStringsWithAutoFixture.aspx">previously
described</a>, each string will be created as a Guid prepended with a named hint –
in this case the argument name. Thus, the phoneNumber argument will get a value like
"phoneNumberfa432351-1563-4769-842c-7588af32a056", which will cause the ParsePhoneNumber
method to throw an exception.
</p>
        <p>
How do we deal with that?
</p>
        <p>
The most obvious fix is to <a href="http://blog.ploeh.dk/2009/04/27/ReplacingAutoFixturesDefaultAlgorithms.aspx">modify
AutoFixture’s algorithm for generating strings</a>. Here 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;\red0\green0\blue255;\red163\green21\blue21;}??\fs20 fixture.Register&lt;\cf3 string\cf0 &gt;(() =&gt; \cf4 "112"\cf0 );}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">fixture.Register&lt;<span style="color: blue">string</span>&gt;(()
=&gt; <span style="color: #a31515">"112"</span>);</pre>
        </div>
        <p>
This will simply cause <em>all</em> generated strings to be "112", including the Contact
instance's Name property. In unit testing, this may not be a problem in itself, since,
from an API perspective, the name could in principle be any string.
</p>
        <p>
However, if the Contact class also had an Email property that was parsed and verified
from a string argument, we'd be in trouble, since "112" is not a valid email address.
</p>
        <p>
We can't easily modify the string generation algorithm to fit the requirements for
both a Danish telephone number and an email address.
</p>
        <p>
Should we then conclude that AutoFixture isn't really useful after all?
</p>
        <p>
On the contrary, this is a hint to us that the Contact class' API could be better.
If an automated tool can't figure out how to generate correct input, how can we expect
other developers to do it?
</p>
        <p>
Although humans can make leaps of intuition, an API should still go to great lengths
to protect its users from making mistakes. Asking for an unbounded string and then
expecting it to be in a particular format may not always be the best option available.
</p>
        <p>
In our particular case, the Value Object pattern offers a better alternative. Our
first version of the DanishPhoneNumber class simply takes an integer as a constructor
argument:
</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 public\cf0  DanishPhoneNumber(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 this\cf0 .number = number;\par ??\}}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <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">this</span>.number
= number;</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
If we still need to parse strings (e.g. from user input), we could add a static Parse,
or even a TryParse, method and test that method in isolation without involving the
Contact class.
</p>
        <p>
This neatly solves our original issue with AutoFixture, since it will now create a
new instance of DanishPhoneNumber as part of the creation process when we ask for
an anonymous Contact instance.
</p>
        <p>
The only remaining issue is that by default, the number fed into the DanishPhoneNumber
instance is likely to be considerably less than 112 – actually, <a href="http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture.aspx">if
no other Int32 instances are created, it will be <em>1</em></a>.
</p>
        <p>
This will be a problem if we modify the DanishPhoneNumber constructor to look like
this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  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-size: 10pt; background: white; color: black; font-family: courier new">
          <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>
Unless a unit test has already caused AutFixture to previously create 111 other integers
(highly unlikely), CreateAnonymous&lt;Contact&gt; is going to throw an exception.
</p>
        <p>
This is easy to fix. Once again, the most obvious fix is to modify the creation algorithm
for integers.
</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;}??\fs20 fixture.Register&lt;\cf3 int\cf0 &gt;(() =&gt; 12345678);}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">fixture.Register&lt;<span style="color: blue">int</span>&gt;(()
=&gt; 12345678);</pre>
        </div>
        <p>
However, this will cause that particular instance of Fixture to return 12345678 <em>every</em> time
you ask it to create an anonymous integer. Depending on the scenario, this may or
may not be a problem.
</p>
        <p>
A more targeted solution is to <a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx">specifically
address the algorithm</a> for generating DanishPhoneNumber instances:
</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 fixture.Register&lt;\cf3 int\cf0 , \cf4 DanishPhoneNumber\cf0 &gt;(i =&gt; \par ??    \cf3 new\cf0  \cf4 DanishPhoneNumber\cf0 (i + 112));}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">fixture.Register&lt;<span style="color: blue">int</span>, <span style="color: #2b91af">DanishPhoneNumber</span>&gt;(i
=&gt; </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">DanishPhoneNumber</span>(i
+ 112));</pre>
        </div>
        <p>
Here, I've even used the Register overload that automatically provides an anonymous
integer to feed into the DanishPhoneNumber constructor, so all I have to do is ensure
that the number falls into the proper range. Adding 112 (the minimum) neatly does
the trick.
</p>
        <p>
If you don't like the hard-coded value of 112 in the test, you can use that to further
drive the design. In this case, we can add a MinValue to DanishPhoneNumber:
</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 fixture.Register&lt;\cf3 int\cf0 , \cf4 DanishPhoneNumber\cf0 &gt;(i =&gt;\par ??    \cf3 new\cf0  \cf4 DanishPhoneNumber\cf0 (i + \par ??        \cf4 DanishPhoneNumber\cf0 .MinValue));}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">fixture.Register&lt;<span style="color: blue">int</span>, <span style="color: #2b91af">DanishPhoneNumber</span>&gt;(i
=&gt;</pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">DanishPhoneNumber</span>(i
+ </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">DanishPhoneNumber</span>.MinValue));</pre>
        </div>
        <p>
Obvously, MinValue will also be used in DanishPhoneNumber's constructor to define
the lower limit of the Guard Clause.
</p>
        <p>
In my opinion, a good API should guide the user and make it difficult to make mistakes.
In many ways, you can view AutoFixture as an exceptionally dim user of your API. This
is the reason I really enjoyed receiving Klaus' original question: Like other TDD
practices, AutoFixture drives better design.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=91aa4494-6b37-4ac9-b268-11493706669f" />
      </body>
      <title>Dealing With Constrained Input</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,91aa4494-6b37-4ac9-b268-11493706669f.aspx</guid>
      <link>http://blog.ploeh.dk/2009/05/01/DealingWithConstrainedInput.aspx</link>
      <pubDate>Fri, 01 May 2009 03:56:00 GMT</pubDate>
      <description>&lt;p&gt;
As a response to my description of &lt;a href="http://blog.ploeh.dk/2009/03/24/HowAutoFixtureCreatesObjects.aspx"&gt;how
AutoFixture creates objects&lt;/a&gt;, Klaus asked:
&lt;/p&gt;
&lt;p&gt;
“[What] if the constructor of ComplexChild imposes some kind of restriction on its
parameter? If, for example, instead of the "name" parameter, it would take a "phoneNumber"
parameter (as a string), and do some format checking?”
&lt;/p&gt;
&lt;p&gt;
Now that we have covered some of the basic features of &lt;a href="http://autofixture.codeplex.com/"&gt;AutoFixture&lt;/a&gt;,
it’s time to properly answer this excellent question.
&lt;/p&gt;
&lt;p&gt;
For simplicity’s sake, let’s assume that the phone number in question is a Danish
phone number: This is pretty good for example code, since a Danish phone number is
essentially just an 8-digit number. It can have white space and an optional country
code (+45), but strip that away, and it’s just an 8-digit number. However, there are
exceptions, since the emergency number is 112 (equivalent to the American 911), and
other 3-digit special numbers exist as well.
&lt;/p&gt;
&lt;p&gt;
With that in mind, let’s look at a simple Contact class that contains a contact’s
name and Danish phone number. The constructor might look like this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  Contact(\cf1 string\cf0  name, \cf1 string\cf0  phoneNumber)\par ??\{\par ??    \cf1 this\cf0 .Name = name;\par ??    \cf1 this\cf0 .PhoneNumber = \par ??        \cf4 Contact\cf0 .ParsePhoneNumber(phoneNumber);\par ??\}}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; Contact(&lt;span style="color: blue"&gt;string&lt;/span&gt; name, &lt;span style="color: blue"&gt;string&lt;/span&gt; phoneNumber)&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;.Name
= name;&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;.PhoneNumber
= &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;Contact&lt;/span&gt;.ParsePhoneNumber(phoneNumber);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The static ParsePhoneNumber method strips away white space and optional country code
and parses the normalized string to a number. This fits the scenario laid out in Klaus’
question.
&lt;/p&gt;
&lt;p&gt;
So what happens when we ask AutoFixture to create an instance of Contact? It will
Reflect over Contact’s constructor and create two new anonymous string instances –
one for name, and one for phoneNumber. As &lt;a href="http://blog.ploeh.dk/2009/04/02/CreatingStringsWithAutoFixture.aspx"&gt;previously
described&lt;/a&gt;, each string will be created as a Guid prepended with a named hint –
in this case the argument name. Thus, the phoneNumber argument will get a value like
"phoneNumberfa432351-1563-4769-842c-7588af32a056", which will cause the ParsePhoneNumber
method to throw an exception.
&lt;/p&gt;
&lt;p&gt;
How do we deal with that?
&lt;/p&gt;
&lt;p&gt;
The most obvious fix is to &lt;a href="http://blog.ploeh.dk/2009/04/27/ReplacingAutoFixturesDefaultAlgorithms.aspx"&gt;modify
AutoFixture’s algorithm for generating strings&lt;/a&gt;. Here 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;\red0\green0\blue255;\red163\green21\blue21;}??\fs20 fixture.Register&amp;lt;\cf3 string\cf0 &amp;gt;(() =&amp;gt; \cf4 "112"\cf0 );}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;fixture.Register&amp;lt;&lt;span style="color: blue"&gt;string&lt;/span&gt;&amp;gt;(()
=&amp;gt; &lt;span style="color: #a31515"&gt;"112"&lt;/span&gt;);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This will simply cause &lt;em&gt;all&lt;/em&gt; generated strings to be "112", including the Contact
instance's Name property. In unit testing, this may not be a problem in itself, since,
from an API perspective, the name could in principle be any string.
&lt;/p&gt;
&lt;p&gt;
However, if the Contact class also had an Email property that was parsed and verified
from a string argument, we'd be in trouble, since "112" is not a valid email address.
&lt;/p&gt;
&lt;p&gt;
We can't easily modify the string generation algorithm to fit the requirements for
both a Danish telephone number and an email address.
&lt;/p&gt;
&lt;p&gt;
Should we then conclude that AutoFixture isn't really useful after all?
&lt;/p&gt;
&lt;p&gt;
On the contrary, this is a hint to us that the Contact class' API could be better.
If an automated tool can't figure out how to generate correct input, how can we expect
other developers to do it?
&lt;/p&gt;
&lt;p&gt;
Although humans can make leaps of intuition, an API should still go to great lengths
to protect its users from making mistakes. Asking for an unbounded string and then
expecting it to be in a particular format may not always be the best option available.
&lt;/p&gt;
&lt;p&gt;
In our particular case, the Value Object pattern offers a better alternative. Our
first version of the DanishPhoneNumber class simply takes an integer as a constructor
argument:
&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 public\cf0  DanishPhoneNumber(\cf1 int\cf0  number)\par ??\{\par ??    \cf1 this\cf0 .number = number;\par ??\}}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&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;this&lt;/span&gt;.number
= number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
If we still need to parse strings (e.g. from user input), we could add a static Parse,
or even a TryParse, method and test that method in isolation without involving the
Contact class.
&lt;/p&gt;
&lt;p&gt;
This neatly solves our original issue with AutoFixture, since it will now create a
new instance of DanishPhoneNumber as part of the creation process when we ask for
an anonymous Contact instance.
&lt;/p&gt;
&lt;p&gt;
The only remaining issue is that by default, the number fed into the DanishPhoneNumber
instance is likely to be considerably less than 112 – actually, &lt;a href="http://blog.ploeh.dk/2009/04/03/CreatingNumbersWithAutoFixture.aspx"&gt;if
no other Int32 instances are created, it will be &lt;em&gt;1&lt;/em&gt;&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
This will be a problem if we modify the DanishPhoneNumber constructor to look like
this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  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-size: 10pt; background: white; color: black; font-family: courier new"&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;
Unless a unit test has already caused AutFixture to previously create 111 other integers
(highly unlikely), CreateAnonymous&amp;lt;Contact&amp;gt; is going to throw an exception.
&lt;/p&gt;
&lt;p&gt;
This is easy to fix. Once again, the most obvious fix is to modify the creation algorithm
for integers.
&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;}??\fs20 fixture.Register&amp;lt;\cf3 int\cf0 &amp;gt;(() =&amp;gt; 12345678);}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;fixture.Register&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;&amp;gt;(()
=&amp;gt; 12345678);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
However, this will cause that particular instance of Fixture to return 12345678 &lt;em&gt;every&lt;/em&gt; time
you ask it to create an anonymous integer. Depending on the scenario, this may or
may not be a problem.
&lt;/p&gt;
&lt;p&gt;
A more targeted solution is to &lt;a href="http://blog.ploeh.dk/2009/04/23/DealingWithTypesWithoutPublicConstructors.aspx"&gt;specifically
address the algorithm&lt;/a&gt; for generating DanishPhoneNumber instances:
&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 fixture.Register&amp;lt;\cf3 int\cf0 , \cf4 DanishPhoneNumber\cf0 &amp;gt;(i =&amp;gt; \par ??    \cf3 new\cf0  \cf4 DanishPhoneNumber\cf0 (i + 112));}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;fixture.Register&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;DanishPhoneNumber&lt;/span&gt;&amp;gt;(i
=&amp;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;DanishPhoneNumber&lt;/span&gt;(i
+ 112));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Here, I've even used the Register overload that automatically provides an anonymous
integer to feed into the DanishPhoneNumber constructor, so all I have to do is ensure
that the number falls into the proper range. Adding 112 (the minimum) neatly does
the trick.
&lt;/p&gt;
&lt;p&gt;
If you don't like the hard-coded value of 112 in the test, you can use that to further
drive the design. In this case, we can add a MinValue to DanishPhoneNumber:
&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 fixture.Register&amp;lt;\cf3 int\cf0 , \cf4 DanishPhoneNumber\cf0 &amp;gt;(i =&amp;gt;\par ??    \cf3 new\cf0  \cf4 DanishPhoneNumber\cf0 (i + \par ??        \cf4 DanishPhoneNumber\cf0 .MinValue));}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;fixture.Register&amp;lt;&lt;span style="color: blue"&gt;int&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;DanishPhoneNumber&lt;/span&gt;&amp;gt;(i
=&amp;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;DanishPhoneNumber&lt;/span&gt;(i
+ &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;DanishPhoneNumber&lt;/span&gt;.MinValue));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Obvously, MinValue will also be used in DanishPhoneNumber's constructor to define
the lower limit of the Guard Clause.
&lt;/p&gt;
&lt;p&gt;
In my opinion, a good API should guide the user and make it difficult to make mistakes.
In many ways, you can view AutoFixture as an exceptionally dim user of your API. This
is the reason I really enjoyed receiving Klaus' original question: Like other TDD
practices, AutoFixture drives better design.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=91aa4494-6b37-4ac9-b268-11493706669f" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,91aa4494-6b37-4ac9-b268-11493706669f.aspx</comments>
      <category>AutoFixture</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2d4133fe-5783-4d22-a592-204fec8aacb4</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2d4133fe-5783-4d22-a592-204fec8aacb4.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2d4133fe-5783-4d22-a592-204fec8aacb4.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2d4133fe-5783-4d22-a592-204fec8aacb4</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When working with the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx">ObjectContext</a> in <a href="http://msdn.microsoft.com/en-us/library/bb386964.aspx">LINQ
To Entities</a>, a lot of operations are easily performed as long as you work with
the same ObjectContext instance: You can retrieve entities from storage by selecting
them; update or delete these entities and create new entities, and the ObjectContext
will keep track of all this for you, so the changes are correctly applied to the store
when you call <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.savechanges.aspx">SaveChanges</a>.
</p>
        <p>
This is all well and good, but not particularly useful when you start working with
layered applications. In this case, LINQ To Entities is just a persistence technology
that you (or someone else) decided to use to implement the Data Access Layer. A few
years ago, I tended to implement my Data Access Components in straight ADO.NET; and
a lot of people prefer <a href="http://nhforge.org/Default.aspx">NHibernate</a> or
similar tools – but I digress…
</p>
        <p>
When LINQ To Entities is just an implementation detail of a service, lifetime management
becomes important, so it is commonly recommended that any ObjectContext instance is
instantiated when needed and disposed immediately after use.
</p>
        <p>
This means that you will have a lot of detached entities in your system. Entities
are likely to be returned to the calling code as interface, and when updating, a client
will simply pass a reference to <em>some</em> implementation of that interface.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 void\cf0  CompleteAtSource(\cf4 IRecord\cf0  record)}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> CompleteAtSource(<span style="color: #2b91af">IRecord</span> record)</pre>
        </div>
        <p>
Since we should always follow the Liskov Substitution Principle, we should not even
try to cast the interface to an entity. Instead, we must populate a new instance of
the entity in question with the correct data and save it.
</p>
        <p>
That’s not hard, but since we are creating a new instance of an entity that represents
data that is already in the database, we must attach it to the ObjectContext so that
it can start tracking it again.
</p>
        <p>
Now we are getting to the heat of the matter, because this is done with the <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attachto.aspx">AttachTo</a> method,
which is woefully inadequately documented.
</p>
        <p>
At first, I couldn’t get it to work, and it wasn’t very apparent to me what I did
wrong, so although the answer is very simple, this post might save you a bit of time.
</p>
        <p>
This was my first attempt:
</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 using\cf0  (\cf4 MessageEntities\cf0  store = \par ??    \cf1 new\cf0  \cf4 MessageEntities\cf0 (\cf1 this\cf0 .connectionString))\par ??\{\par ??    \cf4 Message\cf0  m = \cf1 new\cf0  \cf4 Message\cf0 ();\par ??    m.Id = record.Id;\par ??    m.InputReference = record.InputReference;\par ??    m.State = 2;\par ??    m.Text = record.Text;\par ??\par ??    store.AttachTo(\cf5 "Messages"\cf0 , m);\par ??\par ??    store.SaveChanges();\par ??\}}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">
            <span style="color: blue">using</span> (<span style="color: #2b91af">MessageEntities</span> store
= </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">MessageEntities</span>(<span style="color: blue">this</span>.connectionString))</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Message</span> m
= <span style="color: blue">new</span><span style="color: #2b91af">Message</span>();</pre>
          <pre style="margin: 0px">    m.Id = record.Id;</pre>
          <pre style="margin: 0px">    m.InputReference = record.InputReference;</pre>
          <pre style="margin: 0px">    m.State = 2;</pre>
          <pre style="margin: 0px">    m.Text = record.Text;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    store.AttachTo(<span style="color: #a31515">"Messages"</span>,
m);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    store.SaveChanges();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
I find this approach very intuitive: Build the entity from the input parameter’s data,
attach it to the store and save the changes. Unfortunately, this approach is wrong.
</p>
        <p>
What happens is that when you invoke AttachTo, the state of the entity becomes <a href="http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx">Unchanged</a>,
and thus, not updated.
</p>
        <p>
The solution is so simple that I’m surprised it took me so long to arrive at it: Simply
call AttachTo right after setting the Id property:
</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 using\cf0  (\cf4 MessageEntities\cf0  store = \par ??    \cf1 new\cf0  \cf4 MessageEntities\cf0 (\cf1 this\cf0 .connectionString))\par ??\{\par ??    \cf4 Message\cf0  m = \cf1 new\cf0  \cf4 Message\cf0 ();\par ??    m.Id = record.Id;\par ??\par ??    store.AttachTo(\cf5 "Messages"\cf0 , m);\par ??\par ??    m.InputReference = record.InputReference;\par ??    m.State = 2;\par ??    m.Text = record.Text;\par ??\par ??    store.SaveChanges();\par ??\}}
-->
        <div style="font-size: 10pt; background: white; color: black; font-family: courier new">
          <pre style="margin: 0px">
            <span style="color: blue">using</span> (<span style="color: #2b91af">MessageEntities</span> store
= </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">MessageEntities</span>(<span style="color: blue">this</span>.connectionString))</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Message</span> m
= <span style="color: blue">new</span><span style="color: #2b91af">Message</span>();</pre>
          <pre style="margin: 0px">    m.Id = record.Id;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    store.AttachTo(<span style="color: #a31515">"Messages"</span>,
m);</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    m.InputReference = record.InputReference;</pre>
          <pre style="margin: 0px">    m.State = 2;</pre>
          <pre style="margin: 0px">    m.Text = record.Text;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    store.SaveChanges();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
You can’t invoke AttachTo <em>before</em> adding the Id, since this method requires
that the entity has a populated <a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.entityobject.entitykey.aspx">EntityKey</a> before
it can be attached, but as soon as you begin updating properties <em>after</em> the
call to AttachTo, the entity’s state changes to Modified, and SaveChanges now updates
the data in the database.
</p>
        <p>
That you have to follow this specific sequence when re-attaching data to the ObjectContext
is poorly documented and not enforced by the API, so I thought I’d share this in case
it would save someone else a bit of time.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2d4133fe-5783-4d22-a592-204fec8aacb4" />
      </body>
      <title>Updating Detached Entities With LINQ To Entities</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2d4133fe-5783-4d22-a592-204fec8aacb4.aspx</guid>
      <link>http://blog.ploeh.dk/2009/02/22/UpdatingDetachedEntitiesWithLINQToEntities.aspx</link>
      <pubDate>Sun, 22 Feb 2009 20:45:36 GMT</pubDate>
      <description>&lt;p&gt;
When working with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.aspx"&gt;ObjectContext&lt;/a&gt; in &lt;a href="http://msdn.microsoft.com/en-us/library/bb386964.aspx"&gt;LINQ
To Entities&lt;/a&gt;, a lot of operations are easily performed as long as you work with
the same ObjectContext instance: You can retrieve entities from storage by selecting
them; update or delete these entities and create new entities, and the ObjectContext
will keep track of all this for you, so the changes are correctly applied to the store
when you call &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.savechanges.aspx"&gt;SaveChanges&lt;/a&gt;.
&lt;/p&gt;
&lt;p&gt;
This is all well and good, but not particularly useful when you start working with
layered applications. In this case, LINQ To Entities is just a persistence technology
that you (or someone else) decided to use to implement the Data Access Layer. A few
years ago, I tended to implement my Data Access Components in straight ADO.NET; and
a lot of people prefer &lt;a href="http://nhforge.org/Default.aspx"&gt;NHibernate&lt;/a&gt; or
similar tools – but I digress…
&lt;/p&gt;
&lt;p&gt;
When LINQ To Entities is just an implementation detail of a service, lifetime management
becomes important, so it is commonly recommended that any ObjectContext instance is
instantiated when needed and disposed immediately after use.
&lt;/p&gt;
&lt;p&gt;
This means that you will have a lot of detached entities in your system. Entities
are likely to be returned to the calling code as interface, and when updating, a client
will simply pass a reference to &lt;em&gt;some&lt;/em&gt; implementation of that interface.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 void\cf0  CompleteAtSource(\cf4 IRecord\cf0  record)}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&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; CompleteAtSource(&lt;span style="color: #2b91af"&gt;IRecord&lt;/span&gt; record)&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Since we should always follow the Liskov Substitution Principle, we should not even
try to cast the interface to an entity. Instead, we must populate a new instance of
the entity in question with the correct data and save it.
&lt;/p&gt;
&lt;p&gt;
That’s not hard, but since we are creating a new instance of an entity that represents
data that is already in the database, we must attach it to the ObjectContext so that
it can start tracking it again.
&lt;/p&gt;
&lt;p&gt;
Now we are getting to the heat of the matter, because this is done with the &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.objectcontext.attachto.aspx"&gt;AttachTo&lt;/a&gt; method,
which is woefully inadequately documented.
&lt;/p&gt;
&lt;p&gt;
At first, I couldn’t get it to work, and it wasn’t very apparent to me what I did
wrong, so although the answer is very simple, this post might save you a bit of time.
&lt;/p&gt;
&lt;p&gt;
This was my first attempt:
&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 using\cf0  (\cf4 MessageEntities\cf0  store = \par ??    \cf1 new\cf0  \cf4 MessageEntities\cf0 (\cf1 this\cf0 .connectionString))\par ??\{\par ??    \cf4 Message\cf0  m = \cf1 new\cf0  \cf4 Message\cf0 ();\par ??    m.Id = record.Id;\par ??    m.InputReference = record.InputReference;\par ??    m.State = 2;\par ??    m.Text = record.Text;\par ??\par ??    store.AttachTo(\cf5 "Messages"\cf0 , m);\par ??\par ??    store.SaveChanges();\par ??\}}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;using&lt;/span&gt; (&lt;span style="color: #2b91af"&gt;MessageEntities&lt;/span&gt; store
= &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;MessageEntities&lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.connectionString))&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;Message&lt;/span&gt; m
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Message&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.Id = record.Id;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.InputReference = record.InputReference;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.State = 2;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.Text = record.Text;&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; store.AttachTo(&lt;span style="color: #a31515"&gt;"Messages"&lt;/span&gt;,
m);&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; store.SaveChanges();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I find this approach very intuitive: Build the entity from the input parameter’s data,
attach it to the store and save the changes. Unfortunately, this approach is wrong.
&lt;/p&gt;
&lt;p&gt;
What happens is that when you invoke AttachTo, the state of the entity becomes &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.entitystate.aspx"&gt;Unchanged&lt;/a&gt;,
and thus, not updated.
&lt;/p&gt;
&lt;p&gt;
The solution is so simple that I’m surprised it took me so long to arrive at it: Simply
call AttachTo right after setting the Id property:
&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 using\cf0  (\cf4 MessageEntities\cf0  store = \par ??    \cf1 new\cf0  \cf4 MessageEntities\cf0 (\cf1 this\cf0 .connectionString))\par ??\{\par ??    \cf4 Message\cf0  m = \cf1 new\cf0  \cf4 Message\cf0 ();\par ??    m.Id = record.Id;\par ??\par ??    store.AttachTo(\cf5 "Messages"\cf0 , m);\par ??\par ??    m.InputReference = record.InputReference;\par ??    m.State = 2;\par ??    m.Text = record.Text;\par ??\par ??    store.SaveChanges();\par ??\}}
--&gt;
&lt;div style="font-size: 10pt; background: white; color: black; font-family: courier new"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;using&lt;/span&gt; (&lt;span style="color: #2b91af"&gt;MessageEntities&lt;/span&gt; store
= &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;MessageEntities&lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.connectionString))&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;Message&lt;/span&gt; m
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Message&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.Id = record.Id;&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; store.AttachTo(&lt;span style="color: #a31515"&gt;"Messages"&lt;/span&gt;,
m);&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; m.InputReference = record.InputReference;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.State = 2;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; m.Text = record.Text;&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; store.SaveChanges();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
You can’t invoke AttachTo &lt;em&gt;before&lt;/em&gt; adding the Id, since this method requires
that the entity has a populated &lt;a href="http://msdn.microsoft.com/en-us/library/system.data.objects.dataclasses.entityobject.entitykey.aspx"&gt;EntityKey&lt;/a&gt; before
it can be attached, but as soon as you begin updating properties &lt;em&gt;after&lt;/em&gt; the
call to AttachTo, the entity’s state changes to Modified, and SaveChanges now updates
the data in the database.
&lt;/p&gt;
&lt;p&gt;
That you have to follow this specific sequence when re-attaching data to the ObjectContext
is poorly documented and not enforced by the API, so I thought I’d share this in case
it would save someone else a bit of time.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2d4133fe-5783-4d22-a592-204fec8aacb4" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2d4133fe-5783-4d22-a592-204fec8aacb4.aspx</comments>
      <category>Software Design</category>
    </item>
  </channel>
</rss>