<?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 - Dependency Injection</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=a8872a47-28ce-4726-9a53-51a620cdb4af</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=a8872a47-28ce-4726-9a53-51a620cdb4af</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://structuremap.github.com/structuremap/">StructureMap</a> offers several
different lifetimes, among these two known as <em>PerRequest</em> and <em>Unique</em> respectively.
Recently I found myself wondering what was the difference between those two, but <a href="http://twitter.com/jeremydmiller/statuses/18865954515">a</a><a href="http://twitter.com/jeremydmiller/statuses/18865987309">little</a><a href="http://twitter.com/jeremydmiller/statuses/18866005435">help</a> from <a href="http://codebetter.com/blogs/jeremy.miller/">Jeremy
Miller</a> put me on the right track.
</p>
        <p>
In short, <em>Unique</em> is equivalent to what <a href="http://castleproject.org/container/index.html">Castle
Windsor</a> calls <em>Transient:</em> every time an instance of a type is needed,
a new instance is created. Even if we need the same service multiple times in the
same resolved graph, multiple instances are created.
</p>
        <p>
          <em>PerRequest</em>, on the other hand, is a bit special. Each type can be viewed
as a <em>Singleton</em> within a single call to GetInstance, but as <em>Transient</em> across
different invocations of GetInstance. In other words, the same instance will be shared
within a resolved object graph, but if we resolve the same root type once more, we
will get a new shared instance – a <em>Singleton</em> local to that graph.
</p>
        <p>
Here are some unit tests I wrote to verify this behavior (recall that PerRequest is
StructureMap’s default lifestyle):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 [\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSameUniqueDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&gt;\par ??    \{\par ??        \cf4 var\cf0  unique = \cf4 new\cf0  \cf3 UniquePerRequestLifecycle\cf0 ();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().LifecycleIs(unique)\par ??            .Use&lt;\cf3 Shrimp\cf0 &gt;();\par ??        x.For&lt;\cf3 OliveOil\cf0 &gt;().LifecycleIs(unique);\par ??        x.For&lt;\cf3 EggYolk\cf0 &gt;().LifecycleIs(unique);\par ??        x.For&lt;\cf3 Vinegar\cf0 &gt;().LifecycleIs(unique);\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().LifecycleIs(unique)\par ??            .Use&lt;\cf3 Vinaigrette\cf0 &gt;();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().LifecycleIs(unique)\par ??            .Use&lt;\cf3 Mayonnaise\cf0 &gt;();\par ??        x.For&lt;\cf3 Course\cf0 &gt;().LifecycleIs(unique);\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c1.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil);\par ??\}\par ??\par ??[\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSamePerRequestDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&gt;\par ??    \{\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().Use&lt;\cf3 Shrimp\cf0 &gt;();\par ??        x.For&lt;\cf3 OliveOil\cf0 &gt;();\par ??        x.For&lt;\cf3 EggYolk\cf0 &gt;();\par ??        x.For&lt;\cf3 Vinegar\cf0 &gt;();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().Use&lt;\cf3 Vinaigrette\cf0 &gt;();\par ??        x.For&lt;\cf3 IIngredient\cf0 &gt;().Use&lt;\cf3 Mayonnaise\cf0 &gt;();\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&lt;\cf3 Course\cf0 &gt;();\par ??\par ??    \cf3 Assert\cf0 .Same(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c1.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .Same(\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Mayonnaise\cf0 &gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil,\par ??        c2.Ingredients.OfType&lt;\cf3 Vinaigrette\cf0 &gt;().Single().Oil);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">[<span style="color: #2b91af">Fact</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ResolveServicesWithSameUniqueDependency()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">Container</span>();</pre>
          <pre style="margin: 0px">    container.Configure(x =&gt;</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> unique
= <span style="color: blue">new</span><span style="color: #2b91af">UniquePerRequestLifecycle</span>();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().LifecycleIs(unique)</pre>
          <pre style="margin: 0px">            .Use&lt;<span style="color: #2b91af">Shrimp</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">OliveOil</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">EggYolk</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">Vinegar</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().LifecycleIs(unique)</pre>
          <pre style="margin: 0px">            .Use&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().LifecycleIs(unique)</pre>
          <pre style="margin: 0px">            .Use&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">Course</span>&gt;().LifecycleIs(unique);</pre>
          <pre style="margin: 0px">    });</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c1
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c2
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">[<span style="color: #2b91af">Fact</span>]</pre>
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> ResolveServicesWithSamePerRequestDependency()</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">Container</span>();</pre>
          <pre style="margin: 0px">    container.Configure(x =&gt;</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().Use&lt;<span style="color: #2b91af">Shrimp</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">OliveOil</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">EggYolk</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">Vinegar</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().Use&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;();</pre>
          <pre style="margin: 0px">        x.For&lt;<span style="color: #2b91af">IIngredient</span>&gt;().Use&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;();</pre>
          <pre style="margin: 0px">    });</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c1
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> c2
= container.GetInstance&lt;<span style="color: #2b91af">Course</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.Same(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.Same(</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Mayonnaise</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Assert</span>.NotSame(</pre>
          <pre style="margin: 0px">        c1.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil,</pre>
          <pre style="margin: 0px">        c2.Ingredients.OfType&lt;<span style="color: #2b91af">Vinaigrette</span>&gt;().Single().Oil);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Notice that in both cases, the OliveOil instances are different across two independently
resolved graphs (<em>c1</em> and <em>c2</em>).
</p>
        <p>
However, within each graph, the same OliveOil instance is shared in the <em>PerRequest</em> configuration,
whereas they are different in the <em>Unique</em> configuration.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a8872a47-28ce-4726-9a53-51a620cdb4af" />
      </body>
      <title>StructureMap PerRequest vs. Unique lifetimes</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</guid>
      <link>http://blog.ploeh.dk/2010/07/20/StructureMapPerRequestVsUniqueLifetimes.aspx</link>
      <pubDate>Tue, 20 Jul 2010 20:42:53 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://structuremap.github.com/structuremap/"&gt;StructureMap&lt;/a&gt; offers several
different lifetimes, among these two known as &lt;em&gt;PerRequest&lt;/em&gt; and &lt;em&gt;Unique&lt;/em&gt; respectively.
Recently I found myself wondering what was the difference between those two, but &lt;a href="http://twitter.com/jeremydmiller/statuses/18865954515"&gt;a&lt;/a&gt; &lt;a href="http://twitter.com/jeremydmiller/statuses/18865987309"&gt;little&lt;/a&gt; &lt;a href="http://twitter.com/jeremydmiller/statuses/18866005435"&gt;help&lt;/a&gt; from &lt;a href="http://codebetter.com/blogs/jeremy.miller/"&gt;Jeremy
Miller&lt;/a&gt; put me on the right track.
&lt;/p&gt;
&lt;p&gt;
In short, &lt;em&gt;Unique&lt;/em&gt; is equivalent to what &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt; calls &lt;em&gt;Transient:&lt;/em&gt; every time an instance of a type is needed,
a new instance is created. Even if we need the same service multiple times in the
same resolved graph, multiple instances are created.
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;PerRequest&lt;/em&gt;, on the other hand, is a bit special. Each type can be viewed
as a &lt;em&gt;Singleton&lt;/em&gt; within a single call to GetInstance, but as &lt;em&gt;Transient&lt;/em&gt; across
different invocations of GetInstance. In other words, the same instance will be shared
within a resolved object graph, but if we resolve the same root type once more, we
will get a new shared instance – a &lt;em&gt;Singleton&lt;/em&gt; local to that graph.
&lt;/p&gt;
&lt;p&gt;
Here are some unit tests I wrote to verify this behavior (recall that PerRequest is
StructureMap’s default lifestyle):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 [\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSameUniqueDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&amp;gt;\par ??    \{\par ??        \cf4 var\cf0  unique = \cf4 new\cf0  \cf3 UniquePerRequestLifecycle\cf0 ();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().LifecycleIs(unique)\par ??            .Use&amp;lt;\cf3 Shrimp\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 OliveOil\cf0 &amp;gt;().LifecycleIs(unique);\par ??        x.For&amp;lt;\cf3 EggYolk\cf0 &amp;gt;().LifecycleIs(unique);\par ??        x.For&amp;lt;\cf3 Vinegar\cf0 &amp;gt;().LifecycleIs(unique);\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().LifecycleIs(unique)\par ??            .Use&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().LifecycleIs(unique)\par ??            .Use&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 Course\cf0 &amp;gt;().LifecycleIs(unique);\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil);\par ??\}\par ??\par ??[\cf3 Fact\cf0 ]\par ??\cf4 public\cf0  \cf4 void\cf0  ResolveServicesWithSamePerRequestDependency()\par ??\{\par ??    \cf4 var\cf0  container = \cf4 new\cf0  \cf3 Container\cf0 ();\par ??    container.Configure(x =&amp;gt;\par ??    \{\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().Use&amp;lt;\cf3 Shrimp\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 OliveOil\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 EggYolk\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 Vinegar\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().Use&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;();\par ??        x.For&amp;lt;\cf3 IIngredient\cf0 &amp;gt;().Use&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;();\par ??    \});\par ??\par ??    \cf4 var\cf0  c1 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??    \cf4 var\cf0  c2 = container.GetInstance&amp;lt;\cf3 Course\cf0 &amp;gt;();\par ??\par ??    \cf3 Assert\cf0 .Same(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .Same(\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Mayonnaise\cf0 &amp;gt;().Single().Oil);\par ??    \cf3 Assert\cf0 .NotSame(\par ??        c1.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil,\par ??        c2.Ingredients.OfType&amp;lt;\cf3 Vinaigrette\cf0 &amp;gt;().Single().Oil);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;Fact&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ResolveServicesWithSameUniqueDependency()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Container&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Configure(x =&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; unique
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;UniquePerRequestLifecycle&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().LifecycleIs(unique)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Use&amp;lt;&lt;span style="color: #2b91af"&gt;Shrimp&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;OliveOil&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;EggYolk&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;Vinegar&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().LifecycleIs(unique)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Use&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().LifecycleIs(unique)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .Use&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&gt;&amp;gt;().LifecycleIs(unique);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; c1
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; c2
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;[&lt;span style="color: #2b91af"&gt;Fact&lt;/span&gt;]&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ResolveServicesWithSamePerRequestDependency()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Container&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Configure(x =&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().Use&amp;lt;&lt;span style="color: #2b91af"&gt;Shrimp&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;OliveOil&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;EggYolk&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;Vinegar&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().Use&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; x.For&amp;lt;&lt;span style="color: #2b91af"&gt;IIngredient&lt;/span&gt;&amp;gt;().Use&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; });&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; c1
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; c2
= container.GetInstance&amp;lt;&lt;span style="color: #2b91af"&gt;Course&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.Same(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.Same(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Mayonnaise&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.NotSame(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c1.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; c2.Ingredients.OfType&amp;lt;&lt;span style="color: #2b91af"&gt;Vinaigrette&lt;/span&gt;&amp;gt;().Single().Oil);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that in both cases, the OliveOil instances are different across two independently
resolved graphs (&lt;em&gt;c1&lt;/em&gt; and &lt;em&gt;c2&lt;/em&gt;).
&lt;/p&gt;
&lt;p&gt;
However, within each graph, the same OliveOil instance is shared in the &lt;em&gt;PerRequest&lt;/em&gt; configuration,
whereas they are different in the &lt;em&gt;Unique&lt;/em&gt; configuration.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=a8872a47-28ce-4726-9a53-51a620cdb4af" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,a8872a47-28ce-4726-9a53-51a620cdb4af.aspx</comments>
      <category>Dependency Injection</category>
      <category>StructureMap</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In the next couple of weeks I will be giving a couple of talks in Copenhagen.
</p>
        <p>
At <a href="http://communityday.in/copenhagen/Home/Agenda">Community Day 2010</a> I
will be giving two talks on respectively Dependency Injection and TDD.
</p>
        <p>
In early June I will be giving a <a href="http://www.eventbrite.com/event/660219735">repeat
of my previous CNUG TDD talk</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991" />
      </body>
      <title>Upcoming talks spring 2010</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</guid>
      <link>http://blog.ploeh.dk/2010/05/23/UpcomingTalksSpring2010.aspx</link>
      <pubDate>Sun, 23 May 2010 16:11:37 GMT</pubDate>
      <description>&lt;p&gt;
In the next couple of weeks I will be giving a couple of talks in Copenhagen.
&lt;/p&gt;
&lt;p&gt;
At &lt;a href="http://communityday.in/copenhagen/Home/Agenda"&gt;Community Day 2010&lt;/a&gt; I
will be giving two talks on respectively Dependency Injection and TDD.
&lt;/p&gt;
&lt;p&gt;
In early June I will be giving a &lt;a href="http://www.eventbrite.com/event/660219735"&gt;repeat
of my previous CNUG TDD talk&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=83ccb1fd-21ad-4fd5-bf0b-e61d321f7991" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,83ccb1fd-21ad-4fd5-bf0b-e61d321f7991.aspx</comments>
      <category>Dependency Injection</category>
      <category>Miscellaneous</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=f1a71969-0584-4a15-9395-9f2ac65f104b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=f1a71969-0584-4a15-9395-9f2ac65f104b</wfw:commentRss>
      <slash:comments>6</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
One of Castle Windsor’s facilities addresses wiring up of WCF services. So far, the
sparse documentation for the WCF Facility seems to indicate <a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html">that
you have to configure your container in a global.asax</a>. That’s not much to my liking.
First of all, it reeks of ASP.NET, and secondly, it’s not going to work if you expose
WCF over protocols other than HTTP.
</p>
        <p>
However, now that we know that <a href="http://blog.ploeh.dk/2010/05/17/ServiceHostFactoryLifetime.aspx">a
custom ServiceHostFactory is effectively a Singleton</a>, a much better alternative
is to derive from the WCF Facility’s DefaultServiceHost class:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooServiceHostFactory\cf0  : \par     \cf2 DefaultServiceHostFactory\cf0 \par \{\par     \cf1 public\cf0  FooServiceHostFactory()\par         : \cf1 base\cf0 (\cf2 FooServiceHostFactory\cf0 .CreateKernel())\par     \{\par     \}\par \par     \cf1 private\cf0  \cf1 static\cf0  \cf2 IKernel\cf0  CreateKernel()\par     \{\par         \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par \par         container.AddFacility&lt;\cf2 WcfFacility\cf0 &gt;();\par \par         container.Register(\cf2 Component\cf0 \par             .For&lt;\cf2 FooService\cf0 &gt;()\par             .LifeStyle.Transient);\par         container.Register(\cf2 Component\cf0 \par             .For&lt;\cf2 IBar\cf0 &gt;()\par             .ImplementedBy&lt;\cf2 Bar\cf0 &gt;());\par \par         \cf1 return\cf0  container.Kernel;\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">FooServiceHostFactory</span> : </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">DefaultServiceHostFactory</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> FooServiceHostFactory()</pre>
          <pre style="margin: 0px">        : <span style="color: blue">base</span>(<span style="color: #2b91af">FooServiceHostFactory</span>.CreateKernel())</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">static</span><span style="color: #2b91af">IKernel</span> CreateKernel()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        container.AddFacility&lt;<span style="color: #2b91af">WcfFacility</span>&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">            .For&lt;<span style="color: #2b91af">FooService</span>&gt;()</pre>
          <pre style="margin: 0px">            .LifeStyle.Transient);</pre>
          <pre style="margin: 0px">        container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">            .For&lt;<span style="color: #2b91af">IBar</span>&gt;()</pre>
          <pre style="margin: 0px">            .ImplementedBy&lt;<span style="color: #2b91af">Bar</span>&gt;());</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> container.Kernel;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Although it feels a little odd to create a container and then not really use it, but
only its Kernel property, this works like a charm. It correctly wires up this FooService:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooService\cf0  : \cf2 IFooService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IBar\cf0  bar;\par \par     \cf1 public\cf0  FooService(\cf2 IBar\cf0  bar)\par     \{\par         \cf1 if\cf0  (bar == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "bar"\cf0 );\par         \}\par \par         \cf1 this\cf0 .bar = bar;\par     \}\par \par \cf1     #region\cf0  IFooService Members\par \par     \cf1 public\cf0  \cf1 string\cf0  Foo()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .bar.Baz;\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">FooService</span> : <span style="color: #2b91af">IFooService</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IBar</span> bar;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> FooService(<span style="color: #2b91af">IBar</span> bar)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (bar
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"bar"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.bar
= bar;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IFooService Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">string</span> Foo()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.bar.Baz;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
However, instead of the static CreateKernel method that creates the IKernel instance, <a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/5401a7189f8295af/2dabe6cbb3c63488?q=">I
suggest that the WCF Facility utilizes the Factory Method pattern</a>. As the WCF
Facility has not yet been released, perhaps there’s still time for that change.
</p>
        <p>
In any case, the WCF Facility saves you from writing a lot of infrastructure code
if you would like to wire your WCF services with Castle Windsor.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f1a71969-0584-4a15-9395-9f2ac65f104b" />
      </body>
      <title>Sneak view at Castle’s WCF Facility</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</guid>
      <link>http://blog.ploeh.dk/2010/05/18/SneakViewAtCastlesWCFFacility.aspx</link>
      <pubDate>Tue, 18 May 2010 05:27:56 GMT</pubDate>
      <description>&lt;p&gt;
One of Castle Windsor’s facilities addresses wiring up of WCF services. So far, the
sparse documentation for the WCF Facility seems to indicate &lt;a href="http://www.castleproject.org/container/facilities/trunk/wcf/index.html"&gt;that
you have to configure your container in a global.asax&lt;/a&gt;. That’s not much to my liking.
First of all, it reeks of ASP.NET, and secondly, it’s not going to work if you expose
WCF over protocols other than HTTP.
&lt;/p&gt;
&lt;p&gt;
However, now that we know that &lt;a href="http://blog.ploeh.dk/2010/05/17/ServiceHostFactoryLifetime.aspx"&gt;a
custom ServiceHostFactory is effectively a Singleton&lt;/a&gt;, a much better alternative
is to derive from the WCF Facility’s DefaultServiceHost class:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooServiceHostFactory\cf0  : \par     \cf2 DefaultServiceHostFactory\cf0 \par \{\par     \cf1 public\cf0  FooServiceHostFactory()\par         : \cf1 base\cf0 (\cf2 FooServiceHostFactory\cf0 .CreateKernel())\par     \{\par     \}\par \par     \cf1 private\cf0  \cf1 static\cf0  \cf2 IKernel\cf0  CreateKernel()\par     \{\par         \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par \par         container.AddFacility&amp;lt;\cf2 WcfFacility\cf0 &amp;gt;();\par \par         container.Register(\cf2 Component\cf0 \par             .For&amp;lt;\cf2 FooService\cf0 &amp;gt;()\par             .LifeStyle.Transient);\par         container.Register(\cf2 Component\cf0 \par             .For&amp;lt;\cf2 IBar\cf0 &amp;gt;()\par             .ImplementedBy&amp;lt;\cf2 Bar\cf0 &amp;gt;());\par \par         \cf1 return\cf0  container.Kernel;\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooServiceHostFactory&lt;/span&gt; : &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DefaultServiceHostFactory&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; FooServiceHostFactory()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; : &lt;span style="color: blue"&gt;base&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;FooServiceHostFactory&lt;/span&gt;.CreateKernel())&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IKernel&lt;/span&gt; CreateKernel()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddFacility&amp;lt;&lt;span style="color: #2b91af"&gt;WcfFacility&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;FooService&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .LifeStyle.Transient);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;IBar&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;Bar&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; container.Kernel;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Although it feels a little odd to create a container and then not really use it, but
only its Kernel property, this works like a charm. It correctly wires up this FooService:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooService\cf0  : \cf2 IFooService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IBar\cf0  bar;\par \par     \cf1 public\cf0  FooService(\cf2 IBar\cf0  bar)\par     \{\par         \cf1 if\cf0  (bar == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "bar"\cf0 );\par         \}\par \par         \cf1 this\cf0 .bar = bar;\par     \}\par \par \cf1     #region\cf0  IFooService Members\par \par     \cf1 public\cf0  \cf1 string\cf0  Foo()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .bar.Baz;\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooService&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IFooService&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IBar&lt;/span&gt; bar;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; FooService(&lt;span style="color: #2b91af"&gt;IBar&lt;/span&gt; bar)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (bar
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"bar"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.bar
= bar;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IFooService Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; Foo()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.bar.Baz;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
However, instead of the static CreateKernel method that creates the IKernel instance, &lt;a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/5401a7189f8295af/2dabe6cbb3c63488?q="&gt;I
suggest that the WCF Facility utilizes the Factory Method pattern&lt;/a&gt;. As the WCF
Facility has not yet been released, perhaps there’s still time for that change.
&lt;/p&gt;
&lt;p&gt;
In any case, the WCF Facility saves you from writing a lot of infrastructure code
if you would like to wire your WCF services with Castle Windsor.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=f1a71969-0584-4a15-9395-9f2ac65f104b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,f1a71969-0584-4a15-9395-9f2ac65f104b.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
      <category>Services</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=b0aa9448-ae3b-4b35-a897-54069e8a5c5f</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=b0aa9448-ae3b-4b35-a897-54069e8a5c5f</wfw:commentRss>
      <slash:comments>1</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For a while I’ve been wondering about the lifetime behavior of custom <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory.aspx">ServiceHostFactory</a> classes
hosted in IIS. Does IIS create an instance per request? Or a single instance to handle
all requests?
</p>
        <p>
I decided to find out, so I wrote a little test service. The conclusion seems to be
that there is only a single instance that servers as a factory for all requests. This
is very fortunate, since it gives us an excellent place to host a DI Container. The
container can then manage the lifetime of all components, including Singletons that
will live for the duration of the process.
</p>
        <p>
If you are curious how I arrived at this conclusion, here’s the code I wrote. I started
out with this custom ServiceHostFactory:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 PocServiceHostFactory\cf0  : \cf2 ServiceHostFactory\cf0 \par \{\par     \cf1 private\cf0  \cf1 static\cf0  \cf1 int\cf0  number = 1;\par \par     \cf1 public\cf0  PocServiceHostFactory()\par     \{\par         \cf2 Interlocked\cf0 .Increment(\par             \cf1 ref\cf0  \cf2 PocServiceHostFactory\cf0 .number);\par     \}\par \par     \cf1 protected\cf0  \cf1 override\cf0  \cf2 ServiceHost\cf0  CreateServiceHost(\par         \cf2 Type\cf0  serviceType, \cf2 Uri\cf0 [] baseAddresses)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 PocServiceHost\cf0 (\par             \cf2 PocServiceHostFactory\cf0 .number, serviceType,\par             baseAddresses);\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">PocServiceHostFactory</span> : <span style="color: #2b91af">ServiceHostFactory</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">static</span><span style="color: blue">int</span> number
= 1;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> PocServiceHostFactory()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Interlocked</span>.Increment(</pre>
          <pre style="margin: 0px">            <span style="color: blue">ref</span><span style="color: #2b91af">PocServiceHostFactory</span>.number);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">protected</span><span style="color: blue">override</span><span style="color: #2b91af">ServiceHost</span> CreateServiceHost(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Type</span> serviceType, <span style="color: #2b91af">Uri</span>[]
baseAddresses)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">PocServiceHost</span>(</pre>
          <pre style="margin: 0px">            <span style="color: #2b91af">PocServiceHostFactory</span>.number,
serviceType,</pre>
          <pre style="margin: 0px">            baseAddresses);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The idea is that every time a new instance of ServiceHostFactory is created, the static
number is incremented.
</p>
        <p>
The PocServiceHostFactory just forwards the number to the PocServiceHost:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 PocServiceHost\cf0  : \cf2 ServiceHost\cf0 \par \{\par     \cf1 public\cf0  PocServiceHost(\cf1 int\cf0  number, \cf2 Type\cf0  serviceType,\par         \cf2 Uri\cf0 [] baseAddresses)\par         : \cf1 base\cf0 (serviceType, baseAddresses)\par     \{\par         \cf1 foreach\cf0  (\cf1 var\cf0  cd \cf1 in\cf0  \par             \cf1 this\cf0 .ImplementedContracts.Values)\par         \{\par             cd.Behaviors.Add(\par                 \cf1 new\cf0  \cf2 NumberServiceInstanceProvider\cf0 (\par                     number));\par         \}\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">PocServiceHost</span> : <span style="color: #2b91af">ServiceHost</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> PocServiceHost(<span style="color: blue">int</span> number, <span style="color: #2b91af">Type</span> serviceType,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Uri</span>[]
baseAddresses)</pre>
          <pre style="margin: 0px">        : <span style="color: blue">base</span>(serviceType,
baseAddresses)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">foreach</span> (<span style="color: blue">var</span> cd <span style="color: blue">in</span></pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.ImplementedContracts.Values)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            cd.Behaviors.Add(</pre>
          <pre style="margin: 0px">                <span style="color: blue">new</span><span style="color: #2b91af">NumberServiceInstanceProvider</span>(</pre>
          <pre style="margin: 0px">                    number));</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The PocServiceHost just forwards the number to the NumberServiceInstanceProvider:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 NumberServiceInstanceProvider\cf0  : \par     \cf2 IInstanceProvider\cf0 , \cf2 IContractBehavior\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberServiceInstanceProvider(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  IInstanceProvider Members\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf2 Message\cf0  message)\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .GetInstance(instanceContext);\par     \}\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 NumberService\cf0 (\cf1 this\cf0 .number);\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ReleaseInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf1 object\cf0  instance)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \par \par \cf1     #region\cf0  IContractBehavior Members\par \par     \cf1 public\cf0  \cf1 void\cf0  AddBindingParameters(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 BindingParameterCollection\cf0  bindingParameters)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyClientBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 ClientRuntime\cf0  clientRuntime)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyDispatchBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 DispatchRuntime\cf0  dispatchRuntime)\par     \{\par         dispatchRuntime.InstanceProvider = \cf1 this\cf0 ;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Validate(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">NumberServiceInstanceProvider</span> : </pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IInstanceProvider</span>, <span style="color: #2b91af">IContractBehavior</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">int</span> number;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> NumberServiceInstanceProvider(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.number
= number;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IInstanceProvider Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">object</span> GetInstance(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">InstanceContext</span> instanceContext,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Message</span> message)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.GetInstance(instanceContext);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">object</span> GetInstance(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">InstanceContext</span> instanceContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">new</span><span style="color: #2b91af">NumberService</span>(<span style="color: blue">this</span>.number);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> ReleaseInstance(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">InstanceContext</span> instanceContext,</pre>
          <pre style="margin: 0px">        <span style="color: blue">object</span> instance)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IContractBehavior Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> AddBindingParameters(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">BindingParameterCollection</span> bindingParameters)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> ApplyClientBehavior(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ClientRuntime</span> clientRuntime)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> ApplyDispatchBehavior(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">DispatchRuntime</span> dispatchRuntime)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        dispatchRuntime.InstanceProvider = <span style="color: blue">this</span>;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Validate(</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ContractDescription</span> contractDescription,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ServiceEndpoint</span> endpoint)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The relevant part of NumberServiceInstanceProvider is the GetInstanceMethod that simply
forwards the number to the NumberService:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 NumberService\cf0  : \cf2 INumberService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberService(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  INumberService Members\par \par     \cf1 public\cf0  \cf1 int\cf0  GetNumber()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .number;\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">NumberService</span> : <span style="color: #2b91af">INumberService</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">int</span> number;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> NumberService(<span style="color: blue">int</span> number)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.number
= number;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> INumberService Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">int</span> GetNumber()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span><span style="color: blue">this</span>.number;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
As you can see, NumberService simply returns the injected number.
</p>
        <p>
The experiment is now to host NumberService in IIS using PocServiceHostFactory. If
there is only one ServiceHostFactory per application process, we would expect that
the same number (2) is returned every time we invoke the GetNumber operation. If,
on the other hand, a new instance of ServiceHostFactory is created per request, we
would expect the number to increase for every request.
</p>
        <p>
To test this I spun up a few instances of WcfTestClient.exe and invoked the operation.
It consistently returns <em>2</em> across multiple clients and multiple requests.
This supports the hypothesis that there is only one ServiceHostFactory per service
process.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b0aa9448-ae3b-4b35-a897-54069e8a5c5f" />
      </body>
      <title>ServiceHostFactory lifetime</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</guid>
      <link>http://blog.ploeh.dk/2010/05/17/ServiceHostFactoryLifetime.aspx</link>
      <pubDate>Mon, 17 May 2010 05:42:33 GMT</pubDate>
      <description>&lt;p&gt;
For a while I’ve been wondering about the lifetime behavior of custom &lt;a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.activation.servicehostfactory.aspx"&gt;ServiceHostFactory&lt;/a&gt; classes
hosted in IIS. Does IIS create an instance per request? Or a single instance to handle
all requests?
&lt;/p&gt;
&lt;p&gt;
I decided to find out, so I wrote a little test service. The conclusion seems to be
that there is only a single instance that servers as a factory for all requests. This
is very fortunate, since it gives us an excellent place to host a DI Container. The
container can then manage the lifetime of all components, including Singletons that
will live for the duration of the process.
&lt;/p&gt;
&lt;p&gt;
If you are curious how I arrived at this conclusion, here’s the code I wrote. I started
out with this custom ServiceHostFactory:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 PocServiceHostFactory\cf0  : \cf2 ServiceHostFactory\cf0 \par \{\par     \cf1 private\cf0  \cf1 static\cf0  \cf1 int\cf0  number = 1;\par \par     \cf1 public\cf0  PocServiceHostFactory()\par     \{\par         \cf2 Interlocked\cf0 .Increment(\par             \cf1 ref\cf0  \cf2 PocServiceHostFactory\cf0 .number);\par     \}\par \par     \cf1 protected\cf0  \cf1 override\cf0  \cf2 ServiceHost\cf0  CreateServiceHost(\par         \cf2 Type\cf0  serviceType, \cf2 Uri\cf0 [] baseAddresses)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 PocServiceHost\cf0 (\par             \cf2 PocServiceHostFactory\cf0 .number, serviceType,\par             baseAddresses);\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PocServiceHostFactory&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;ServiceHostFactory&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; number
= 1;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; PocServiceHostFactory()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Interlocked&lt;/span&gt;.Increment(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;ref&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PocServiceHostFactory&lt;/span&gt;.number);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;protected&lt;/span&gt; &lt;span style="color: blue"&gt;override&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ServiceHost&lt;/span&gt; CreateServiceHost(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Type&lt;/span&gt; serviceType, &lt;span style="color: #2b91af"&gt;Uri&lt;/span&gt;[]
baseAddresses)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PocServiceHost&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;PocServiceHostFactory&lt;/span&gt;.number,
serviceType,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; baseAddresses);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The idea is that every time a new instance of ServiceHostFactory is created, the static
number is incremented.
&lt;/p&gt;
&lt;p&gt;
The PocServiceHostFactory just forwards the number to the PocServiceHost:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 PocServiceHost\cf0  : \cf2 ServiceHost\cf0 \par \{\par     \cf1 public\cf0  PocServiceHost(\cf1 int\cf0  number, \cf2 Type\cf0  serviceType,\par         \cf2 Uri\cf0 [] baseAddresses)\par         : \cf1 base\cf0 (serviceType, baseAddresses)\par     \{\par         \cf1 foreach\cf0  (\cf1 var\cf0  cd \cf1 in\cf0  \par             \cf1 this\cf0 .ImplementedContracts.Values)\par         \{\par             cd.Behaviors.Add(\par                 \cf1 new\cf0  \cf2 NumberServiceInstanceProvider\cf0 (\par                     number));\par         \}\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;PocServiceHost&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;ServiceHost&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; PocServiceHost(&lt;span style="color: blue"&gt;int&lt;/span&gt; number, &lt;span style="color: #2b91af"&gt;Type&lt;/span&gt; serviceType,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Uri&lt;/span&gt;[]
baseAddresses)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; : &lt;span style="color: blue"&gt;base&lt;/span&gt;(serviceType,
baseAddresses)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;foreach&lt;/span&gt; (&lt;span style="color: blue"&gt;var&lt;/span&gt; cd &lt;span style="color: blue"&gt;in&lt;/span&gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.ImplementedContracts.Values)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; cd.Behaviors.Add(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NumberServiceInstanceProvider&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; number));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The PocServiceHost just forwards the number to the NumberServiceInstanceProvider:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 NumberServiceInstanceProvider\cf0  : \par     \cf2 IInstanceProvider\cf0 , \cf2 IContractBehavior\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberServiceInstanceProvider(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  IInstanceProvider Members\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf2 Message\cf0  message)\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .GetInstance(instanceContext);\par     \}\par \par     \cf1 public\cf0  \cf1 object\cf0  GetInstance(\par         \cf2 InstanceContext\cf0  instanceContext)\par     \{\par         \cf1 return\cf0  \cf1 new\cf0  \cf2 NumberService\cf0 (\cf1 this\cf0 .number);\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ReleaseInstance(\par         \cf2 InstanceContext\cf0  instanceContext,\par         \cf1 object\cf0  instance)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \par \par \cf1     #region\cf0  IContractBehavior Members\par \par     \cf1 public\cf0  \cf1 void\cf0  AddBindingParameters(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 BindingParameterCollection\cf0  bindingParameters)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyClientBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 ClientRuntime\cf0  clientRuntime)\par     \{\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  ApplyDispatchBehavior(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint,\par         \cf2 DispatchRuntime\cf0  dispatchRuntime)\par     \{\par         dispatchRuntime.InstanceProvider = \cf1 this\cf0 ;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Validate(\par         \cf2 ContractDescription\cf0  contractDescription,\par         \cf2 ServiceEndpoint\cf0  endpoint)\par     \{\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NumberServiceInstanceProvider&lt;/span&gt; : &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IInstanceProvider&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;IContractBehavior&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; NumberServiceInstanceProvider(&lt;span style="color: blue"&gt;int&lt;/span&gt; number)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.number
= number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IInstanceProvider Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;object&lt;/span&gt; GetInstance(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;InstanceContext&lt;/span&gt; instanceContext,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Message&lt;/span&gt; message)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.GetInstance(instanceContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;object&lt;/span&gt; GetInstance(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;InstanceContext&lt;/span&gt; instanceContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NumberService&lt;/span&gt;(&lt;span style="color: blue"&gt;this&lt;/span&gt;.number);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ReleaseInstance(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;InstanceContext&lt;/span&gt; instanceContext,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;object&lt;/span&gt; instance)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IContractBehavior Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; AddBindingParameters(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ContractDescription&lt;/span&gt; contractDescription,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ServiceEndpoint&lt;/span&gt; endpoint,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;BindingParameterCollection&lt;/span&gt; bindingParameters)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ApplyClientBehavior(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ContractDescription&lt;/span&gt; contractDescription,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ServiceEndpoint&lt;/span&gt; endpoint,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ClientRuntime&lt;/span&gt; clientRuntime)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ApplyDispatchBehavior(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ContractDescription&lt;/span&gt; contractDescription,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ServiceEndpoint&lt;/span&gt; endpoint,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DispatchRuntime&lt;/span&gt; dispatchRuntime)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; dispatchRuntime.InstanceProvider = &lt;span style="color: blue"&gt;this&lt;/span&gt;;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Validate(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ContractDescription&lt;/span&gt; contractDescription,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ServiceEndpoint&lt;/span&gt; endpoint)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The relevant part of NumberServiceInstanceProvider is the GetInstanceMethod that simply
forwards the number to the NumberService:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 NumberService\cf0  : \cf2 INumberService\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 int\cf0  number;\par \par     \cf1 public\cf0  NumberService(\cf1 int\cf0  number)\par     \{\par         \cf1 this\cf0 .number = number;\par     \}\par \par \cf1     #region\cf0  INumberService Members\par \par     \cf1 public\cf0  \cf1 int\cf0  GetNumber()\par     \{\par         \cf1 return\cf0  \cf1 this\cf0 .number;\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;NumberService&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;INumberService&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; NumberService(&lt;span style="color: blue"&gt;int&lt;/span&gt; number)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.number
= number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; INumberService Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; GetNumber()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;this&lt;/span&gt;.number;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
As you can see, NumberService simply returns the injected number.
&lt;/p&gt;
&lt;p&gt;
The experiment is now to host NumberService in IIS using PocServiceHostFactory. If
there is only one ServiceHostFactory per application process, we would expect that
the same number (2) is returned every time we invoke the GetNumber operation. If,
on the other hand, a new instance of ServiceHostFactory is created per request, we
would expect the number to increase for every request.
&lt;/p&gt;
&lt;p&gt;
To test this I spun up a few instances of WcfTestClient.exe and invoked the operation.
It consistently returns &lt;em&gt;2&lt;/em&gt; across multiple clients and multiple requests.
This supports the hypothesis that there is only one ServiceHostFactory per service
process.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=b0aa9448-ae3b-4b35-a897-54069e8a5c5f" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,b0aa9448-ae3b-4b35-a897-54069e8a5c5f.aspx</comments>
      <category>Dependency Injection</category>
      <category>Services</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=589220df-9778-41a9-a7df-e0543901bb2b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=589220df-9778-41a9-a7df-e0543901bb2b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://www.manning.com/seemann/">My book</a> contains a section on the <a href="http://blogs.msdn.com/ploeh/archive/2007/07/23/AmbientContext.aspx">Ambient
Context</a> pattern that uses a TimeProvider as an example. It’s used like this:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 this\cf0 .closedAt = \cf4 TimeProvider\cf0 .Current.UtcNow;}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">this</span>.closedAt
= <span style="color: #2b91af">TimeProvider</span>.Current.UtcNow;</pre>
        </div>
        <p>
Yesterday I was TDDing a state machine that consumes TimeProvider and needed to freeze
and advance time at different places in the test. Always on the lookout for making
unit tests more readable, I decided to have a little fun with literal extensions and
TimeProvider. I ended up with this test:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  fixture = \cf3 new\cf0  \cf5 WcfFixture\cf0 ();\par ??\par ??\cf5 DateTime\cf0 .Now.Freeze();\par ??\par ??fixture.Register(1.Minutes());\par ??\cf3 var\cf0  sut = fixture.CreateAnonymous&lt;\cf5 CircuitBreaker\cf0 &gt;();\par ??sut.PutInOpenState();\par ??\par ??2.Minutes().Pass();\par ??\cf1 // Exercise system\par ??\cf0 sut.Guard();\par ??\cf1 // Verify outcome\par ??\cf5 Assert\cf0 .IsInstanceOfType(sut.State,\par ??    \cf3 typeof\cf0 (\cf5 HalfOpenCircuitState\cf0 ));\par ??\cf1 // Teardown}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: green">//
Fixture setup</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> fixture
= <span style="color: blue">new</span><span style="color: #2b91af">WcfFixture</span>();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">DateTime</span>.Now.Freeze();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">fixture.Register(1.Minutes());</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= fixture.CreateAnonymous&lt;<span style="color: #2b91af">CircuitBreaker</span>&gt;();</pre>
          <pre style="margin: 0px">sut.PutInOpenState();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">2.Minutes().Pass();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Exercise system</span>
          </pre>
          <pre style="margin: 0px">sut.Guard();</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Verify outcome</span>
          </pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">Assert</span>.IsInstanceOfType(sut.State,</pre>
          <pre style="margin: 0px">    <span style="color: blue">typeof</span>(<span style="color: #2b91af">HalfOpenCircuitState</span>));</pre>
          <pre style="margin: 0px">
            <span style="color: green">//
Teardown</span>
          </pre>
        </div>
        <p>
There are several items of note. Imagine that we can freeze time!
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 DateTime\cf0 .Now.Freeze();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: #2b91af">DateTime</span>.Now.Freeze();</pre>
        </div>
        <p>
With the TimeProvider and an extension method, we can:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 static\cf0  \cf1 void\cf0  Freeze(\cf1 this\cf0  \cf4 DateTime\cf0  dt)\par ??\{\par ??    \cf1 var\cf0  timeProviderStub = \cf1 new\cf0  \cf4 Mock\cf0 &lt;\cf4 TimeProvider\cf0 &gt;();\par ??    timeProviderStub.SetupGet(tp =&gt; tp.UtcNow).Returns(dt);\par ??    \cf4 TimeProvider\cf0 .Current = timeProviderStub.Object;\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">internal</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Freeze(<span style="color: blue">this</span><span style="color: #2b91af">DateTime</span> dt)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> timeProviderStub
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">TimeProvider</span>&gt;();</pre>
          <pre style="margin: 0px">    timeProviderStub.SetupGet(tp =&gt; tp.UtcNow).Returns(dt);</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">TimeProvider</span>.Current
= timeProviderStub.Object;</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
This effectively sets up the TimeProvider to always return the same time.
</p>
        <p>
Later in the test I state that 2 minutes pass:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;}??\fs20 2.Minutes().Pass();}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">2.Minutes().Pass();</pre>
        </div>
        <p>
I particularly like the grammatically correct English. This is accomplished with a
combination of a literal extension and changing the state of TimeProvider.
</p>
        <p>
First, the literal extension:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 static\cf0  \cf4 TimeSpan\cf0  Minutes(\cf1 this\cf0  \cf1 int\cf0  m)\par ??\{\par ??    \cf1 return\cf0  \cf4 TimeSpan\cf0 .FromMinutes(m);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">internal</span>
            <span style="color: blue">static</span>
            <span style="color: #2b91af">TimeSpan</span> Minutes(<span style="color: blue">this</span><span style="color: blue">int</span> m)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span><span style="color: #2b91af">TimeSpan</span>.FromMinutes(m);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Given the TimeSpan returned from the Minutes method, I can now invoke the Pass extension
method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 static\cf0  \cf1 void\cf0  Pass(\cf1 this\cf0  \cf4 TimeSpan\cf0  ts)\par ??\{\par ??    \cf1 var\cf0  previousTime = \cf4 TimeProvider\cf0 .Current.UtcNow;\par ??    (previousTime + ts).Freeze();\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">internal</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Pass(<span style="color: blue">this</span><span style="color: #2b91af">TimeSpan</span> ts)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> previousTime
= <span style="color: #2b91af">TimeProvider</span>.Current.UtcNow;</pre>
          <pre style="margin: 0px">    (previousTime + ts).Freeze();</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Note that I just add the TimeSpan to the current time and invoke the Freeze extension
method with the new value.
</p>
        <p>
Last, but not least, I should point out that the PutInOpenState method isn’t some
smelly test-specific method on the <a href="http://xunitpatterns.com/SUT.html">SUT</a>,
but rather yet another extension method.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=589220df-9778-41a9-a7df-e0543901bb2b" />
      </body>
      <title>Fun with literal extensions and Ambient Context</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/27/FunWithLiteralExtensionsAndAmbientContext.aspx</link>
      <pubDate>Tue, 27 Apr 2010 04:24:25 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://www.manning.com/seemann/"&gt;My book&lt;/a&gt; contains a section on the &lt;a href="http://blogs.msdn.com/ploeh/archive/2007/07/23/AmbientContext.aspx"&gt;Ambient
Context&lt;/a&gt; pattern that uses a TimeProvider as an example. It’s used like this:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 this\cf0 .closedAt = \cf4 TimeProvider\cf0 .Current.UtcNow;}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;this&lt;/span&gt;.closedAt
= &lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;.Current.UtcNow;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Yesterday I was TDDing a state machine that consumes TimeProvider and needed to freeze
and advance time at different places in the test. Always on the lookout for making
unit tests more readable, I decided to have a little fun with literal extensions and
TimeProvider. I ended up with this test:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green128\blue0;\red255\green255\blue255;\red0\green0\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 // Fixture setup\par ??\cf3 var\cf0  fixture = \cf3 new\cf0  \cf5 WcfFixture\cf0 ();\par ??\par ??\cf5 DateTime\cf0 .Now.Freeze();\par ??\par ??fixture.Register(1.Minutes());\par ??\cf3 var\cf0  sut = fixture.CreateAnonymous&amp;lt;\cf5 CircuitBreaker\cf0 &amp;gt;();\par ??sut.PutInOpenState();\par ??\par ??2.Minutes().Pass();\par ??\cf1 // Exercise system\par ??\cf0 sut.Guard();\par ??\cf1 // Verify outcome\par ??\cf5 Assert\cf0 .IsInstanceOfType(sut.State,\par ??    \cf3 typeof\cf0 (\cf5 HalfOpenCircuitState\cf0 ));\par ??\cf1 // Teardown}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Fixture setup&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; fixture
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WcfFixture&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Now.Freeze();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;fixture.Register(1.Minutes());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= fixture.CreateAnonymous&amp;lt;&lt;span style="color: #2b91af"&gt;CircuitBreaker&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.PutInOpenState();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;2.Minutes().Pass();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Exercise system&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.Guard();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Verify outcome&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;Assert&lt;/span&gt;.IsInstanceOfType(sut.State,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;span style="color: #2b91af"&gt;HalfOpenCircuitState&lt;/span&gt;));&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: green"&gt;//
Teardown&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
There are several items of note. Imagine that we can freeze time!
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red43\green145\blue175;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 DateTime\cf0 .Now.Freeze();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt;.Now.Freeze();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With the TimeProvider and an extension method, we can:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 static\cf0  \cf1 void\cf0  Freeze(\cf1 this\cf0  \cf4 DateTime\cf0  dt)\par ??\{\par ??    \cf1 var\cf0  timeProviderStub = \cf1 new\cf0  \cf4 Mock\cf0 &amp;lt;\cf4 TimeProvider\cf0 &amp;gt;();\par ??    timeProviderStub.SetupGet(tp =&amp;gt; tp.UtcNow).Returns(dt);\par ??    \cf4 TimeProvider\cf0 .Current = timeProviderStub.Object;\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;internal&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Freeze(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: #2b91af"&gt;DateTime&lt;/span&gt; dt)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; timeProviderStub
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; timeProviderStub.SetupGet(tp =&amp;gt; tp.UtcNow).Returns(dt);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;.Current
= timeProviderStub.Object;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This effectively sets up the TimeProvider to always return the same time.
&lt;/p&gt;
&lt;p&gt;
Later in the test I state that 2 minutes pass:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;}??\fs20 2.Minutes().Pass();}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;2.Minutes().Pass();&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I particularly like the grammatically correct English. This is accomplished with a
combination of a literal extension and changing the state of TimeProvider.
&lt;/p&gt;
&lt;p&gt;
First, the literal extension:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 static\cf0  \cf4 TimeSpan\cf0  Minutes(\cf1 this\cf0  \cf1 int\cf0  m)\par ??\{\par ??    \cf1 return\cf0  \cf4 TimeSpan\cf0 .FromMinutes(m);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;internal&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt; Minutes(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: blue"&gt;int&lt;/span&gt; m)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt;.FromMinutes(m);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Given the TimeSpan returned from the Minutes method, I can now invoke the Pass extension
method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 internal\cf0  \cf1 static\cf0  \cf1 void\cf0  Pass(\cf1 this\cf0  \cf4 TimeSpan\cf0  ts)\par ??\{\par ??    \cf1 var\cf0  previousTime = \cf4 TimeProvider\cf0 .Current.UtcNow;\par ??    (previousTime + ts).Freeze();\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;internal&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Pass(&lt;span style="color: blue"&gt;this&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TimeSpan&lt;/span&gt; ts)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; previousTime
= &lt;span style="color: #2b91af"&gt;TimeProvider&lt;/span&gt;.Current.UtcNow;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; (previousTime + ts).Freeze();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Note that I just add the TimeSpan to the current time and invoke the Freeze extension
method with the new value.
&lt;/p&gt;
&lt;p&gt;
Last, but not least, I should point out that the PutInOpenState method isn’t some
smelly test-specific method on the &lt;a href="http://xunitpatterns.com/SUT.html"&gt;SUT&lt;/a&gt;,
but rather yet another extension method.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=589220df-9778-41a9-a7df-e0543901bb2b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,589220df-9778-41a9-a7df-e0543901bb2b.aspx</comments>
      <category>Dependency Injection</category>
      <category>Unit Testing</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=ce797146-6cc9-4322-b40d-990395d69e36</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ce797146-6cc9-4322-b40d-990395d69e36</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I recently had the need to change the lifestyles of all components in a WindsorContainer
(read on to the end if you want to know why). This turned out to be amazingly simple
to do.
</p>
        <p>
The problem was this: I had numerous components registered in a WindsorContainer,
some of them as Singletons, some as Transients and yet again some as PerWebRequest.
Configuration was even defined in numerous IWindsorInstallers, including some distributed
XML files. I now needed to spin up a second container with the same configuration
as the first one, <em>except</em> that the lifestyles should be all Singletons across
the board.
</p>
        <p>
This can be easily accomplished by implementing a custom IContributeComponentModelConstruction
type. Here’s a simple example:
</p>
        <p>
Consider this IWindsorInstaller:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooInstaller\cf0  : \cf2 IWindsorInstaller\cf0 \par \{\par \cf1     #region\cf0  IWindsorInstaller Members\par \par     \cf1 public\cf0  \cf1 void\cf0  Install(\cf2 IWindsorContainer\cf0  container,\par         \cf2 IConfigurationStore\cf0  store)\par     \{\par         container.Register(\cf2 Component\cf0 \par             .For&lt;\cf2 IFoo\cf0 &gt;()\par             .ImplementedBy&lt;\cf2 Foo\cf0 &gt;()\par             .LifeStyle.Transient);\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">FooInstaller</span> : <span style="color: #2b91af">IWindsorInstaller</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IWindsorInstaller Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Install(<span style="color: #2b91af">IWindsorContainer</span> container,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">IConfigurationStore</span> store)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        container.Register(<span style="color: #2b91af">Component</span></pre>
          <pre style="margin: 0px">            .For&lt;<span style="color: #2b91af">IFoo</span>&gt;()</pre>
          <pre style="margin: 0px">            .ImplementedBy&lt;<span style="color: #2b91af">Foo</span>&gt;()</pre>
          <pre style="margin: 0px">            .LifeStyle.Transient);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The important point to notice is that it registers the lifestyle as Transient. In
other words, this container will always return new Foo instances:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();</pre>
          <pre style="margin: 0px">container.Install(<span style="color: blue">new</span><span style="color: #2b91af">FooInstaller</span>());</pre>
        </div>
        <p>
We can override this behavior by adding this custom IContributeComponentModelConstruction:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 SingletonEqualizer\cf0  :\par     \cf2 IContributeComponentModelConstruction\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  ProcessModel(\cf2 IKernel\cf0  kernel, \par         \cf2 ComponentModel\cf0  model)\par     \{\par         model.LifestyleType = \cf2 LifestyleType\cf0 .Singleton;\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">SingletonEqualizer</span> :</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">IContributeComponentModelConstruction</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> ProcessModel(<span style="color: #2b91af">IKernel</span> kernel, </pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ComponentModel</span> model)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        model.LifestyleType = <span style="color: #2b91af">LifestyleType</span>.Singleton;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In this very simple example, I always set the lifestyle type to the same value, but
obviously we can write as complex code in the ProcessModel method as we would like.
We can now configure the container like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Kernel.ComponentModelBuilder\par     .AddContributor(\cf1 new\cf0  \cf2 SingletonEqualizer\cf0 ());\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> container
= <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();</pre>
          <pre style="margin: 0px">container.Kernel.ComponentModelBuilder</pre>
          <pre style="margin: 0px">    .AddContributor(<span style="color: blue">new</span><span style="color: #2b91af">SingletonEqualizer</span>());</pre>
          <pre style="margin: 0px">container.Install(<span style="color: blue">new</span><span style="color: #2b91af">FooInstaller</span>());</pre>
        </div>
        <p>
With this configuration we will now get the same instance of Foo every time we Resolve
IFoo.
</p>
        <p>
We did I need this? Because my application is a web application and I’m using the
PerWebRequest lifestyle in a number of places. However, I needed to spin up a second
container that would compose object hierarchies for a background process. This background
process needs the same component configuration as the rest of the application, but
can’t use the PerWebRequest lifestyle as there will be no web request available to
the background process. Hence the need to change lifestyles across the board.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ce797146-6cc9-4322-b40d-990395d69e36" />
      </body>
      <title>Changing Windsor lifestyles after the fact</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</guid>
      <link>http://blog.ploeh.dk/2010/04/26/ChangingWindsorLifestylesAfterTheFact.aspx</link>
      <pubDate>Mon, 26 Apr 2010 05:09:42 GMT</pubDate>
      <description>&lt;p&gt;
I recently had the need to change the lifestyles of all components in a WindsorContainer
(read on to the end if you want to know why). This turned out to be amazingly simple
to do.
&lt;/p&gt;
&lt;p&gt;
The problem was this: I had numerous components registered in a WindsorContainer,
some of them as Singletons, some as Transients and yet again some as PerWebRequest.
Configuration was even defined in numerous IWindsorInstallers, including some distributed
XML files. I now needed to spin up a second container with the same configuration
as the first one, &lt;em&gt;except&lt;/em&gt; that the lifestyles should be all Singletons across
the board.
&lt;/p&gt;
&lt;p&gt;
This can be easily accomplished by implementing a custom IContributeComponentModelConstruction
type. Here’s a simple example:
&lt;/p&gt;
&lt;p&gt;
Consider this IWindsorInstaller:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 FooInstaller\cf0  : \cf2 IWindsorInstaller\cf0 \par \{\par \cf1     #region\cf0  IWindsorInstaller Members\par \par     \cf1 public\cf0  \cf1 void\cf0  Install(\cf2 IWindsorContainer\cf0  container,\par         \cf2 IConfigurationStore\cf0  store)\par     \{\par         container.Register(\cf2 Component\cf0 \par             .For&amp;lt;\cf2 IFoo\cf0 &amp;gt;()\par             .ImplementedBy&amp;lt;\cf2 Foo\cf0 &amp;gt;()\par             .LifeStyle.Transient);\par     \}\par \par \cf1     #endregion\cf0 \par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooInstaller&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IWindsorInstaller&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IWindsorInstaller Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Install(&lt;span style="color: #2b91af"&gt;IWindsorContainer&lt;/span&gt; container,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IConfigurationStore&lt;/span&gt; store)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;IFoo&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;Foo&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .LifeStyle.Transient);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The important point to notice is that it registers the lifestyle as Transient. In
other words, this container will always return new Foo instances:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Install(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooInstaller&lt;/span&gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We can override this behavior by adding this custom IContributeComponentModelConstruction:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 SingletonEqualizer\cf0  :\par     \cf2 IContributeComponentModelConstruction\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  ProcessModel(\cf2 IKernel\cf0  kernel, \par         \cf2 ComponentModel\cf0  model)\par     \{\par         model.LifestyleType = \cf2 LifestyleType\cf0 .Singleton;\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SingletonEqualizer&lt;/span&gt; :&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IContributeComponentModelConstruction&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ProcessModel(&lt;span style="color: #2b91af"&gt;IKernel&lt;/span&gt; kernel, &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ComponentModel&lt;/span&gt; model)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; model.LifestyleType = &lt;span style="color: #2b91af"&gt;LifestyleType&lt;/span&gt;.Singleton;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this very simple example, I always set the lifestyle type to the same value, but
obviously we can write as complex code in the ProcessModel method as we would like.
We can now configure the container like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  container = \cf1 new\cf0  \cf2 WindsorContainer\cf0 ();\par container.Kernel.ComponentModelBuilder\par     .AddContributor(\cf1 new\cf0  \cf2 SingletonEqualizer\cf0 ());\par container.Install(\cf1 new\cf0  \cf2 FooInstaller\cf0 ());\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; container
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Kernel.ComponentModelBuilder&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .AddContributor(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SingletonEqualizer&lt;/span&gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Install(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;FooInstaller&lt;/span&gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With this configuration we will now get the same instance of Foo every time we Resolve
IFoo.
&lt;/p&gt;
&lt;p&gt;
We did I need this? Because my application is a web application and I’m using the
PerWebRequest lifestyle in a number of places. However, I needed to spin up a second
container that would compose object hierarchies for a background process. This background
process needs the same component configuration as the rest of the application, but
can’t use the PerWebRequest lifestyle as there will be no web request available to
the background process. Hence the need to change lifestyles across the board.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ce797146-6cc9-4322-b40d-990395d69e36" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,ce797146-6cc9-4322-b40d-990395d69e36.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=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=89bf0c61-5cf2-4e92-8b53-fa0a10d06945</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=89bf0c61-5cf2-4e92-8b53-fa0a10d06945</wfw:commentRss>
      <slash:comments>20</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Service Locator is a well-known pattern, and since it was <a href="http://martinfowler.com/articles/injection.html">described
by Martin Fowler</a>, it must be good, right?
</p>
        <p>
No, it’s actually an <strong>anti-pattern</strong> and should be avoided.
</p>
        <p>
Let’s examine why this is so. In short, the problem with Service Locator is that it
hides a class’ dependencies, causing run-time errors instead of compile-time errors,
as well as making the code more difficult to maintain because it becomes unclear when
you would be introducing a breaking change.
</p>
        <p>
          <strong>OrderProcessor example</strong>
        </p>
        <p>
As an example, let’s pick a hot topic in DI these days: an OrderProcessor. To process
an order, the OrderProcessor must validate the order and ship it if valid. Here’s
an example using a static Service Locator:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">OrderProcessor</span> : <span style="color: #2b91af">IOrderProcessor</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> validator
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> shipper
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">            shipper.Ship(order);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The Service Locator is used as a replacement for the <em>new</em> operator. It looks
like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&lt;T&gt;(\cf2 Func\cf0 &lt;T&gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&gt; resolver();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  T Resolve&lt;T&gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">static</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Locator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">static</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;</pre>
          <pre style="margin: 0px">        services = <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Register&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;T&gt;
resolver)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]
= () =&gt; resolver();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span> T
Resolve&lt;T&gt;()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> (T)<span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Reset()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services.Clear();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
We can configure the Locator using the Register method. A ‘real’ Service Locator implementation
would be much more advanced than this, but this example captures the gist of it.
</p>
        <p>
This is flexible and extensible, and it even supports replacing services with Test
Doubles, as we will see shortly.
</p>
        <p>
Given that, then what could be the problem?
</p>
        <p>
          <strong>API usage issues</strong>
        </p>
        <p>
Let’s assume for a moment that we are simply consumers of the OrderProcessor class.
We didn’t write it ourselves, it was given to us in an assembly by a third party,
and we have yet to look at it in Reflector.
</p>
        <p>
This is what we get from IntelliSense in Visual Studio:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_3.png" width="317" height="52" />
        </p>
        <p>
Okay, so the class has a default constructor. That means I can simply create a new
instance of it and invoke the Process method right away:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 ();\par sut.Process(order);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= <span style="color: blue">new</span><span style="color: #2b91af">Order</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">OrderProcessor</span>();</pre>
          <pre style="margin: 0px">sut.Process(order);</pre>
        </div>
        <p>
Alas, running this code surprisingly throws a KeyNotFoundException because the IOrderValidator
was never registered with Locator. This is not only surprising, it may be quite baffling
if we don’t have access to the source code.
</p>
        <p>
By perusing the source code (or using Reflector) or consulting the documentation (ick!)
we may finally discover that we need to register an IOrderValidator instance with
Locator (a completely unrelated static class) before this will work.
</p>
        <p>
In a unit test test, this can be done like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  validatorStub = \cf1 new\cf0  \cf2 Mock\cf0 &lt;\cf2 IOrderValidator\cf0 &gt;();\par validatorStub.Setup(v =&gt; v.Validate(order)).Returns(\cf1 false\cf0 );\par \cf2 Locator\cf0 .Register(() =&gt; validatorStub.Object);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> validatorStub
= <span style="color: blue">new</span><span style="color: #2b91af">Mock</span>&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">validatorStub.Setup(v =&gt; v.Validate(order)).Returns(<span style="color: blue">false</span>);</pre>
          <pre style="margin: 0px">
            <span style="color: #2b91af">Locator</span>.Register(()
=&gt; validatorStub.Object);</pre>
        </div>
        <p>
What is even more annoying is that because the Locator’s internal store is static,
we need to invoke the Reset method after each unit test, but granted: that is mainly
a unit testing issue.
</p>
        <p>
All in all, however, we can’t reasonably claim that this sort of API provides a positive
developer experience.
</p>
        <p>
          <strong>Maintenance issues</strong>
        </p>
        <p>
While this use of Service Locator is problematic from the consumer’s point of view,
what seems easy soon becomes an issue for the maintenance developer as well.
</p>
        <p>
Let’s say that we need to expand the behavior of OrderProcessor to also invoke the <a href="http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx">IOrderCollector.Collect
method</a>. This is easily done, or is it?
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  collector = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderCollector\cf0 &gt;();\par         collector.Collect(order);\par         \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> validator
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> collector
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderCollector</span>&gt;();</pre>
          <pre style="margin: 0px">        collector.Collect(order);</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> shipper
= <span style="color: #2b91af">Locator</span>.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">        shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
From a pure mechanistic point of view, that was easy – we simply added a new call
to Locator.Resolve and invoke IOrderCollector.Collect.
</p>
        <p>
Was this a breaking change?
</p>
        <p>
This can be surprisingly hard to answer. It certainly compiled fine, but broke one
of my unit tests. What happens in a production application? The IOrderCollector interface
may already be registered with the Service Locator because it is already in use by
other components, in which case it will work without a hitch. On the other hand, this
may not be the case.
</p>
        <p>
The bottom line is that it becomes a lot harder to tell whether you are introducing
a breaking change or not. You need to understand the <em>entire</em> application in
which the Service Locator is being used, and the compiler is not going to help you.
</p>
        <p>
          <strong>Variation: Concrete Service Locator</strong>
        </p>
        <p>
Can we fix these issues in some way?
</p>
        <p>
One variation commonly encountered is to make the Service Locator a concrete class,
used like this:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par     \cf1 var\cf0  validator = locator.Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  shipper = locator.Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> locator
= <span style="color: blue">new</span><span style="color: #2b91af">Locator</span>();</pre>
          <pre style="margin: 0px">    <span style="color: blue">var</span> validator
= locator.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> shipper
= locator.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">        shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
However, to be configured, it still needs a static in-memory store:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&lt;T&gt;(\cf2 Func\cf0 &lt;T&gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&lt;T&gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Locator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: blue">static</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;</pre>
          <pre style="margin: 0px">        services = <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;();</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Register&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;T&gt;
resolver)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]
= () =&gt; resolver();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> T
Resolve&lt;T&gt;()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> (T)<span style="color: #2b91af">Locator</span>.services[<span style="color: blue">typeof</span>(T)]();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">static</span><span style="color: blue">void</span> Reset()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Locator</span>.services.Clear();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In other words: there’s no structural difference between the concrete Service Locator
and the static Service Locator we already reviewed. It has the same issues and solves
nothing.
</p>
        <p>
          <strong>Variation: Abstract Service Locator</strong>
        </p>
        <p>
A different variation seems more in line with true DI: the Service Locator is a concrete
class implementing an interface.
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 interface\cf0  \cf2 IServiceLocator\cf0 \par \{\par     T Resolve&lt;T&gt;();\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IServiceLocator</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    T Resolve&lt;T&gt;();</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
        </div>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0  : \cf2 IServiceLocator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt; services;\par \par     \cf1 public\cf0  Locator()\par     \{\par         \cf1 this\cf0 .services = \cf1 new\cf0  \cf2 Dictionary\cf0 &lt;\cf2 Type\cf0 , \cf2 Func\cf0 &lt;\cf1 object\cf0 &gt;&gt;();\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Register&lt;T&gt;(\cf2 Func\cf0 &lt;T&gt; resolver)\par     \{\par         \cf1 this\cf0 .services[\cf1 typeof\cf0 (T)] = () =&gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&lt;T&gt;()\par     \{\par         \cf1 return\cf0  (T)\cf1 this\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">Locator</span> : <span style="color: #2b91af">IServiceLocator</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;
services;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> Locator()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.services
= <span style="color: blue">new</span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">Type</span>, <span style="color: #2b91af">Func</span>&lt;<span style="color: blue">object</span>&gt;&gt;();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Register&lt;T&gt;(<span style="color: #2b91af">Func</span>&lt;T&gt;
resolver)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.services[<span style="color: blue">typeof</span>(T)]
= () =&gt; resolver();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> T
Resolve&lt;T&gt;()</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">return</span> (T)<span style="color: blue">this</span>.services[<span style="color: blue">typeof</span>(T)]();</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
With this variation it becomes necessary to inject the Service Locator into the consumer. <strong>Constructor
Injection</strong> is always a good choice for injecting dependencies, so OrderProcessor
morphs into this implementation:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IServiceLocator\cf0  locator;\par \par     \cf1 public\cf0  OrderProcessor(\cf2 IServiceLocator\cf0  locator)\par     \{\par         \cf1 if\cf0  (locator == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "locator"\cf0 );\par         \}\par \par         \cf1 this\cf0 .locator = locator;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \par             \cf1 this\cf0 .locator.Resolve&lt;\cf2 IOrderValidator\cf0 &gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper =\par                 \cf1 this\cf0 .locator.Resolve&lt;\cf2 IOrderShipper\cf0 &gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">OrderProcessor</span> : <span style="color: #2b91af">IOrderProcessor</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IServiceLocator</span> locator;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> OrderProcessor(<span style="color: #2b91af">IServiceLocator</span> locator)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (locator
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"locator"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.locator
= locator;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">var</span> validator
= </pre>
          <pre style="margin: 0px">            <span style="color: blue">this</span>.locator.Resolve&lt;<span style="color: #2b91af">IOrderValidator</span>&gt;();</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (validator.Validate(order))</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">var</span> shipper
=</pre>
          <pre style="margin: 0px">                <span style="color: blue">this</span>.locator.Resolve&lt;<span style="color: #2b91af">IOrderShipper</span>&gt;();</pre>
          <pre style="margin: 0px">            shipper.Ship(order);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Is this good, then?
</p>
        <p>
From a developer perspective, we now get a bit of help from IntelliSense:
</p>
        <p>
          <img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_6.png" width="474" height="47" />
        </p>
        <p>
What does this tell us? Nothing much, really. Okay, so OrderProcessor needs a ServiceLocator
– that’s a bit more information than before, but it still doesn’t tell us <em>which
services</em> are needed. The following code compiles, but crashes with the same KeyNotFoundException
as before:
</p>
        <!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 (locator);\par sut.Process(order);\par }
-->
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">var</span> order
= <span style="color: blue">new</span><span style="color: #2b91af">Order</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> locator
= <span style="color: blue">new</span><span style="color: #2b91af">Locator</span>();</pre>
          <pre style="margin: 0px">
            <span style="color: blue">var</span> sut
= <span style="color: blue">new</span><span style="color: #2b91af">OrderProcessor</span>(locator);</pre>
          <pre style="margin: 0px">sut.Process(order);</pre>
        </div>
        <p>
From the maintenance developer’s point of view, things don’t improve much either.
We still get no help if we need to add a new dependency: is it a breaking change or
not? Just as hard to tell as before.
</p>
        <p>
          <strong>Summary</strong>
        </p>
        <p>
The problem with using a Service Locator isn’t that you take a dependency on a particular
Service Locator implementation (although that may be a problem as well), but that
it’s a bona-fide <strong>anti-pattern</strong>. It will give consumers of your API
a horrible developer experience, and it will make your life as a maintenance developer
worse because you will need to use considerable amounts of brain power to grasp the
implications of every change you make.
</p>
        <p>
The compiler can offer both consumers and producers so much help when <strong>Constructor
Injection</strong> is used, but none of that assistance is available for APIs that
rely on Service Locator.
</p>
        <p>
You can read more about DI patterns and anti-patterns in <a href="http://www.manning.com/seemann/">my
upcoming book</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=89bf0c61-5cf2-4e92-8b53-fa0a10d06945" />
      </body>
      <title>Service Locator is an Anti-Pattern</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</guid>
      <link>http://blog.ploeh.dk/2010/02/03/ServiceLocatorIsAnAntiPattern.aspx</link>
      <pubDate>Wed, 03 Feb 2010 21:49:39 GMT</pubDate>
      <description>&lt;p&gt;
Service Locator is a well-known pattern, and since it was &lt;a href="http://martinfowler.com/articles/injection.html"&gt;described
by Martin Fowler&lt;/a&gt;, it must be good, right?
&lt;/p&gt;
&lt;p&gt;
No, it’s actually an &lt;strong&gt;anti-pattern&lt;/strong&gt; and should be avoided.
&lt;/p&gt;
&lt;p&gt;
Let’s examine why this is so. In short, the problem with Service Locator is that it
hides a class’ dependencies, causing run-time errors instead of compile-time errors,
as well as making the code more difficult to maintain because it becomes unclear when
you would be introducing a breaking change.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;OrderProcessor example&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
As an example, let’s pick a hot topic in DI these days: an OrderProcessor. To process
an order, the OrderProcessor must validate the order and ship it if valid. Here’s
an example using a static Service Locator:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderProcessor&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The Service Locator is used as a replacement for the &lt;em&gt;new&lt;/em&gt; operator. It looks
like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 static\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&amp;lt;T&amp;gt;(\cf2 Func\cf0 &amp;lt;T&amp;gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&amp;gt; resolver();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  T Resolve&amp;lt;T&amp;gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; services = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Register&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
resolver)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]
= () =&amp;gt; resolver();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; T
Resolve&amp;lt;T&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; (T)&lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Reset()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services.Clear();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
We can configure the Locator using the Register method. A ‘real’ Service Locator implementation
would be much more advanced than this, but this example captures the gist of it.
&lt;/p&gt;
&lt;p&gt;
This is flexible and extensible, and it even supports replacing services with Test
Doubles, as we will see shortly.
&lt;/p&gt;
&lt;p&gt;
Given that, then what could be the problem?
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;API usage issues&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Let’s assume for a moment that we are simply consumers of the OrderProcessor class.
We didn’t write it ourselves, it was given to us in an assembly by a third party,
and we have yet to look at it in Reflector.
&lt;/p&gt;
&lt;p&gt;
This is what we get from IntelliSense in Visual Studio:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_3.png" width="317" height="52"&gt; 
&lt;/p&gt;
&lt;p&gt;
Okay, so the class has a default constructor. That means I can simply create a new
instance of it and invoke the Process method right away:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 ();\par sut.Process(order);\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.Process(order);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Alas, running this code surprisingly throws a KeyNotFoundException because the IOrderValidator
was never registered with Locator. This is not only surprising, it may be quite baffling
if we don’t have access to the source code.
&lt;/p&gt;
&lt;p&gt;
By perusing the source code (or using Reflector) or consulting the documentation (ick!)
we may finally discover that we need to register an IOrderValidator instance with
Locator (a completely unrelated static class) before this will work.
&lt;/p&gt;
&lt;p&gt;
In a unit test test, this can be done like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  validatorStub = \cf1 new\cf0  \cf2 Mock\cf0 &amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par validatorStub.Setup(v =&amp;gt; v.Validate(order)).Returns(\cf1 false\cf0 );\par \cf2 Locator\cf0 .Register(() =&amp;gt; validatorStub.Object);\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; validatorStub
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Mock&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;validatorStub.Setup(v =&amp;gt; v.Validate(order)).Returns(&lt;span style="color: blue"&gt;false&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Register(()
=&amp;gt; validatorStub.Object);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What is even more annoying is that because the Locator’s internal store is static,
we need to invoke the Reset method after each unit test, but granted: that is mainly
a unit testing issue.
&lt;/p&gt;
&lt;p&gt;
All in all, however, we can’t reasonably claim that this sort of API provides a positive
developer experience.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Maintenance issues&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
While this use of Service Locator is problematic from the consumer’s point of view,
what seems easy soon becomes an issue for the maintenance developer as well.
&lt;/p&gt;
&lt;p&gt;
Let’s say that we need to expand the behavior of OrderProcessor to also invoke the &lt;a href="http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx"&gt;IOrderCollector.Collect
method&lt;/a&gt;. This is easily done, or is it?
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  validator = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  collector = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderCollector\cf0 &amp;gt;();\par         collector.Collect(order);\par         \cf1 var\cf0  shipper = \cf2 Locator\cf0 .Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; collector
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; collector.Collect(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
From a pure mechanistic point of view, that was easy – we simply added a new call
to Locator.Resolve and invoke IOrderCollector.Collect.
&lt;/p&gt;
&lt;p&gt;
Was this a breaking change?
&lt;/p&gt;
&lt;p&gt;
This can be surprisingly hard to answer. It certainly compiled fine, but broke one
of my unit tests. What happens in a production application? The IOrderCollector interface
may already be registered with the Service Locator because it is already in use by
other components, in which case it will work without a hitch. On the other hand, this
may not be the case.
&lt;/p&gt;
&lt;p&gt;
The bottom line is that it becomes a lot harder to tell whether you are introducing
a breaking change or not. You need to understand the &lt;em&gt;entire&lt;/em&gt; application in
which the Service Locator is being used, and the compiler is not going to help you.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Variation: Concrete Service Locator&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
Can we fix these issues in some way?
&lt;/p&gt;
&lt;p&gt;
One variation commonly encountered is to make the Service Locator a concrete class,
used like this:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par \{\par     \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par     \cf1 var\cf0  validator = locator.Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par     \cf1 if\cf0  (validator.Validate(order))\par     \{\par         \cf1 var\cf0  shipper = locator.Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par         shipper.Ship(order);\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; locator
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
= locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
However, to be configured, it still needs a static in-memory store:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf1 static\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;\par         services = \cf1 new\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;();\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Register&amp;lt;T&amp;gt;(\cf2 Func\cf0 &amp;lt;T&amp;gt; resolver)\par     \{\par         \cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)] = () =&amp;gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&amp;lt;T&amp;gt;()\par     \{\par         \cf1 return\cf0  (T)\cf2 Locator\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \par     \cf1 public\cf0  \cf1 static\cf0  \cf1 void\cf0  Reset()\par     \{\par         \cf2 Locator\cf0 .services.Clear();\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; services = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Register&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
resolver)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]
= () =&amp;gt; resolver();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; T
Resolve&amp;lt;T&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; (T)&lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Reset()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;.services.Clear();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In other words: there’s no structural difference between the concrete Service Locator
and the static Service Locator we already reviewed. It has the same issues and solves
nothing.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Variation: Abstract Service Locator&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
A different variation seems more in line with true DI: the Service Locator is a concrete
class implementing an interface.
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 interface\cf0  \cf2 IServiceLocator\cf0 \par \{\par     T Resolve&amp;lt;T&amp;gt;();\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;interface&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; T Resolve&amp;lt;T&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;
&lt;/div&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 Locator\cf0  : \cf2 IServiceLocator\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt; services;\par \par     \cf1 public\cf0  Locator()\par     \{\par         \cf1 this\cf0 .services = \cf1 new\cf0  \cf2 Dictionary\cf0 &amp;lt;\cf2 Type\cf0 , \cf2 Func\cf0 &amp;lt;\cf1 object\cf0 &amp;gt;&amp;gt;();\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Register&amp;lt;T&amp;gt;(\cf2 Func\cf0 &amp;lt;T&amp;gt; resolver)\par     \{\par         \cf1 this\cf0 .services[\cf1 typeof\cf0 (T)] = () =&amp;gt; resolver();\par     \}\par \par     \cf1 public\cf0  T Resolve&amp;lt;T&amp;gt;()\par     \{\par         \cf1 return\cf0  (T)\cf1 this\cf0 .services[\cf1 typeof\cf0 (T)]();\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;
services;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; Locator()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.services
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Dictionary&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Type&lt;/span&gt;, &lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;&lt;span style="color: blue"&gt;object&lt;/span&gt;&amp;gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Register&amp;lt;T&amp;gt;(&lt;span style="color: #2b91af"&gt;Func&lt;/span&gt;&amp;lt;T&amp;gt;
resolver)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]
= () =&amp;gt; resolver();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; T
Resolve&amp;lt;T&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; (T)&lt;span style="color: blue"&gt;this&lt;/span&gt;.services[&lt;span style="color: blue"&gt;typeof&lt;/span&gt;(T)]();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With this variation it becomes necessary to inject the Service Locator into the consumer. &lt;strong&gt;Constructor
Injection&lt;/strong&gt; is always a good choice for injecting dependencies, so OrderProcessor
morphs into this implementation:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;\red163\green21\blue21;}\f0 \fs19 \cf1 public\cf0  \cf1 class\cf0  \cf2 OrderProcessor\cf0  : \cf2 IOrderProcessor\cf0 \par \{\par     \cf1 private\cf0  \cf1 readonly\cf0  \cf2 IServiceLocator\cf0  locator;\par \par     \cf1 public\cf0  OrderProcessor(\cf2 IServiceLocator\cf0  locator)\par     \{\par         \cf1 if\cf0  (locator == \cf1 null\cf0 )\par         \{\par             \cf1 throw\cf0  \cf1 new\cf0  \cf2 ArgumentNullException\cf0 (\cf3 "locator"\cf0 );\par         \}\par \par         \cf1 this\cf0 .locator = locator;\par     \}\par \par     \cf1 public\cf0  \cf1 void\cf0  Process(\cf2 Order\cf0  order)\par     \{\par         \cf1 var\cf0  validator = \par             \cf1 this\cf0 .locator.Resolve&amp;lt;\cf2 IOrderValidator\cf0 &amp;gt;();\par         \cf1 if\cf0  (validator.Validate(order))\par         \{\par             \cf1 var\cf0  shipper =\par                 \cf1 this\cf0 .locator.Resolve&amp;lt;\cf2 IOrderShipper\cf0 &amp;gt;();\par             shipper.Ship(order);\par         \}\par     \}\par \}\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderProcessor&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt; locator;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; OrderProcessor(&lt;span style="color: #2b91af"&gt;IServiceLocator&lt;/span&gt; locator)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (locator
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"locator"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.locator
= locator;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; validator
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (validator.Validate(order))&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; shipper
=&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.locator.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt;&amp;gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Is this good, then?
&lt;/p&gt;
&lt;p&gt;
From a developer perspective, we now get a bit of help from IntelliSense:
&lt;/p&gt;
&lt;p&gt;
&lt;img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://blog.ploeh.dk/content/binary/WindowsLiveWriter/ServiceLocatorisanAntiPattern_F652/image_6.png" width="474" height="47"&gt; 
&lt;/p&gt;
&lt;p&gt;
What does this tell us? Nothing much, really. Okay, so OrderProcessor needs a ServiceLocator
– that’s a bit more information than before, but it still doesn’t tell us &lt;em&gt;which
services&lt;/em&gt; are needed. The following code compiles, but crashes with the same KeyNotFoundException
as before:
&lt;/p&gt;
&lt;!--
{\rtf\ansi{\fonttbl{\f0 Consolas;}}{\colortbl;\red0\green0\blue255;\red43\green145\blue175;}\f0 \fs19 \cf1 var\cf0  order = \cf1 new\cf0  \cf2 Order\cf0 ();\par \cf1 var\cf0  locator = \cf1 new\cf0  \cf2 Locator\cf0 ();\par \cf1 var\cf0  sut = \cf1 new\cf0  \cf2 OrderProcessor\cf0 (locator);\par sut.Process(order);\par }
--&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; order
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Order&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; locator
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;Locator&lt;/span&gt;();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;var&lt;/span&gt; sut
= &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderProcessor&lt;/span&gt;(locator);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;sut.Process(order);&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
From the maintenance developer’s point of view, things don’t improve much either.
We still get no help if we need to add a new dependency: is it a breaking change or
not? Just as hard to tell as before.
&lt;/p&gt;
&lt;p&gt;
&lt;strong&gt;Summary&lt;/strong&gt;
&lt;/p&gt;
&lt;p&gt;
The problem with using a Service Locator isn’t that you take a dependency on a particular
Service Locator implementation (although that may be a problem as well), but that
it’s a bona-fide &lt;strong&gt;anti-pattern&lt;/strong&gt;. It will give consumers of your API
a horrible developer experience, and it will make your life as a maintenance developer
worse because you will need to use considerable amounts of brain power to grasp the
implications of every change you make.
&lt;/p&gt;
&lt;p&gt;
The compiler can offer both consumers and producers so much help when &lt;strong&gt;Constructor
Injection&lt;/strong&gt; is used, but none of that assistance is available for APIs that
rely on Service Locator.
&lt;/p&gt;
&lt;p&gt;
You can read more about DI patterns and anti-patterns in &lt;a href="http://www.manning.com/seemann/"&gt;my
upcoming book&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=89bf0c61-5cf2-4e92-8b53-fa0a10d06945" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,89bf0c61-5cf2-4e92-8b53-fa0a10d06945.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a <a href="http://jeffreypalermo.com/blog/constructor-over-injection-smell-ndash-follow-up/">follow-up</a> to
his <a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/">earlier
post on Constructor Over-Injection</a>, <a href="http://jeffreypalermo.com/">Jeffrey
Palermo</a> changes his stance on Constructor Over-Injection from <em>anti-pattern</em> to
the more palatable <em>code smell</em>. In this post I introduce the concept of an <strong>Aggregate
Service</strong> and outline a refactoring that addresses this code smell.
</p>
        <p>
If I should extract a core message from Jeffrey Palermo’s blog post it would be that
it’s a code smell if you have a class that takes too many dependencies in its constructor.
</p>
        <p>
I can only agree, but only so far as it’s a code smell. However, it has nothing to
do with DI in general or <strong>Constructor Injection</strong> specifically. Rather,
it’s a smell that indicates a violation of the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> (SRP). Let’s review the example constructor:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IAccountsReceivable\cf0  receivable,\par ??                      \cf4 IRateExchange\cf0  exchange,\par ??                      \cf4 IUserContext\cf0  userContext)}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> OrderProcessor(<span style="color: #2b91af">IOrderValidator</span> validator,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IOrderShipper</span> shipper,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IAccountsReceivable</span> receivable,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IRateExchange</span> exchange,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IUserContext</span> userContext)</pre>
        </div>
        <p>
In this version, I even added IOrderShipper back in <a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx">as
I described in my earlier post</a>. Surely, five constructor parameters are too many.
</p>
        <p>
          <em>
            <strong>Constructor Injection</strong> makes SRP violations glaringly obvious.</em>
        </p>
        <p>
What’s not to like? My personal threshold lies somewhere around 3-4 constructor parameters,
so whenever I hit three, I start to consider if I could perhaps aggregate some of
the dependencies into a new type.
</p>
        <p>
I call such a type an <strong>Aggregate Service</strong>. It’s closely related to <a href="http://www.refactoring.com/catalog/introduceParameterObject.html">Parameter
Objects</a>, but the main difference is that a <strong>Parameter Object</strong> only
moves the parameters to a common root, while an <strong>Aggregate Service</strong> hides
the aggregate behavior behind a new abstraction. While the <strong>Aggregate Service</strong> may
start its life as a result of a pure mechanistic refactoring, it often turns out that
the extracted behavior represents a Domain Concept in its own right. Congratulations:
you’ve just move a little closer to adhering to the SRP!
</p>
        <p>
Let’s look at Jeffrey Palermo’s OrderProcessor example. The core implementation of
the class is reproduced here (recall that in my version, IOrderShipper is also an
injected dependency):
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf4 SuccessResult\cf0  Process(\cf4 Order\cf0  order)\par ??\{\par ??    \cf1 bool\cf0  isValid = _validator.Validate(order);\par ??    \cf1 if\cf0  (isValid)\par ??    \{\par ??        Collect(order);\par ??        _shipper.Ship(order);\par ??    \}\par ??\par ??    \cf1 return\cf0  CreateStatus(isValid);\par ??\}\par ??\par ??\cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??    \cf4 Price\cf0  price = order.GetPrice(_exchange, _userContext);\par ??    _receivable.Collect(user, price);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: #2b91af">SuccessResult</span> Process(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">bool</span> isValid
= _validator.Validate(order);</pre>
          <pre style="margin: 0px">    <span style="color: blue">if</span> (isValid)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        Collect(order);</pre>
          <pre style="margin: 0px">        _shipper.Ship(order);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">return</span> CreateStatus(isValid);</pre>
          <pre style="margin: 0px">}</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">User</span> user
= _userContext.GetCurrentUser();</pre>
          <pre style="margin: 0px">    <span style="color: #2b91af">Price</span> price
= order.GetPrice(_exchange, _userContext);</pre>
          <pre style="margin: 0px">    _receivable.Collect(user, price);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
If you examine the code it should quickly become apparent that the Collect method
encapsulates a cluster of dependencies: IAccountsReceivable, IRateExchange and IUserContext.
In this case it’s pretty obvious because they are already encapsulated in a single
private method. In real production code, you may need to perform a series of internal
refactorings before a pattern starts to emerge and you can extract an interface that
aggregates several dependencies.
</p>
        <p>
Now that we have identified the cluster of dependencies, we can extract an interface
that closely resembles the Collect method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 void\cf0  Collect(\cf4 Order\cf0  order);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">interface</span>
            <span style="color: #2b91af">IOrderCollector</span>
          </pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
In lieu of a better name, I simply chose to call it IOrderCollector, but what’s interesting
about extracting <strong>Aggregate Services</strong> is that over time, they often
turn out to be previously <em>implicit</em> Domain Concepts that we have now dragged
out in the open and made <em>explicit</em>.
</p>
        <p>
We can now inject IOrderCollector into OrderProcessor and change the implementation
of the private Collect method:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    _collector.Collect(order);\par ??\}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    _collector.Collect(order);</pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Next, we can remove the redundant dependencies, leaving us with this constructor:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IOrderCollector\cf0  collector)}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span> OrderProcessor(<span style="color: #2b91af">IOrderValidator</span> validator,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IOrderShipper</span> shipper,</pre>
          <pre style="margin: 0px">                      <span style="color: #2b91af">IOrderCollector</span> collector)</pre>
        </div>
        <p>
With three constructor parameters it’s much more acceptable, but we can always consider
repeating the procedure and extract a new <strong>Aggregate Service</strong> that
aggregates IOrderShipper and IOrderCollector.
</p>
        <p>
The original behavior from the Collect method is still required, but is now implemented
in the OrderCollector class:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 OrderCollector\cf0  : \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IUserContext\cf0  _userContext;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IRateExchange\cf0  _exchange;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IAccountsReceivable\cf0  _receivable;\par ??\par ??    \cf1 public\cf0  OrderCollector(\cf4 IAccountsReceivable\cf0  receivable,\par ??                          \cf4 IRateExchange\cf0  exchange,\par ??                          \cf4 IUserContext\cf0  userContext)\par ??    \{\par ??        _receivable = receivable;\par ??        _exchange = exchange;\par ??        _userContext = userContext;\par ??    \}\par ??\par ??\cf1     #region\cf0  IOrderCollector Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??        \cf4 Price\cf0  price = \par ??            order.GetPrice(_exchange, _userContext);\par ??        _receivable.Collect(user, price);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">OrderCollector</span> : <span style="color: #2b91af">IOrderCollector</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IUserContext</span> _userContext;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IRateExchange</span> _exchange;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IAccountsReceivable</span> _receivable;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> OrderCollector(<span style="color: #2b91af">IAccountsReceivable</span> receivable,</pre>
          <pre style="margin: 0px">                          <span style="color: #2b91af">IRateExchange</span> exchange,</pre>
          <pre style="margin: 0px">                          <span style="color: #2b91af">IUserContext</span> userContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        _receivable = receivable;</pre>
          <pre style="margin: 0px">        _exchange = exchange;</pre>
          <pre style="margin: 0px">        _userContext = userContext;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IOrderCollector Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> Collect(<span style="color: #2b91af">Order</span> order)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">User</span> user
= _userContext.GetCurrentUser();</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">Price</span> price
= </pre>
          <pre style="margin: 0px">            order.GetPrice(_exchange, _userContext);</pre>
          <pre style="margin: 0px">        _receivable.Collect(user, price);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
Here’s another class with three constructor parameters, which falls within the reasonable
range. However, once again, we can begin to consider whether the interaction between
IUserContext and the Order could be better modeled.
</p>
        <p>
In outline form, the <em>Introduce Aggregate Service</em> refactoring follows these
steps:
</p>
        <ol>
          <li>
Analyze how dependencies interact to identify clusters of behavior. 
</li>
          <li>
Extract an interface from these clusters. 
</li>
          <li>
Copy the original implementation to a class that implements the new interface. 
</li>
          <li>
Inject the new interface into the consumer. 
</li>
          <li>
Replace the original implementation with a call the new dependency. 
</li>
          <li>
Remove the redundant dependencies. 
</li>
          <li>
Rinse and repeat :)</li>
        </ol>
        <p>
The beauty of <strong>Aggregate Services</strong> is that we can keep wrapping one <strong>Aggregate
Service</strong> in new <strong>Aggregate Services</strong> to define more and more
coarse-grained building blocks as we get closer and closer to the application boundary.
</p>
        <p>
Keeping each class and its dependencies to simple interactions also makes it much
easier to unit test all of them because none of them do anything particularly complex.
</p>
        <p>
Adhering strictly to <strong>Constructor Injection</strong> makes it easy to see when
one violates the SRP and should refactor to an <strong>Aggregate Service</strong>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5" />
      </body>
      <title>Refactoring to Aggregate Services</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</guid>
      <link>http://blog.ploeh.dk/2010/02/02/RefactoringToAggregateServices.aspx</link>
      <pubDate>Tue, 02 Feb 2010 20:56:44 GMT</pubDate>
      <description>&lt;p&gt;
In a &lt;a href="http://jeffreypalermo.com/blog/constructor-over-injection-smell-ndash-follow-up/"&gt;follow-up&lt;/a&gt; to
his &lt;a href="http://jeffreypalermo.com/blog/constructor-over-injection-anti-pattern/"&gt;earlier
post on Constructor Over-Injection&lt;/a&gt;, &lt;a href="http://jeffreypalermo.com/"&gt;Jeffrey
Palermo&lt;/a&gt; changes his stance on Constructor Over-Injection from &lt;em&gt;anti-pattern&lt;/em&gt; to
the more palatable &lt;em&gt;code smell&lt;/em&gt;. In this post I introduce the concept of an &lt;strong&gt;Aggregate
Service&lt;/strong&gt; and outline a refactoring that addresses this code smell.
&lt;/p&gt;
&lt;p&gt;
If I should extract a core message from Jeffrey Palermo’s blog post it would be that
it’s a code smell if you have a class that takes too many dependencies in its constructor.
&lt;/p&gt;
&lt;p&gt;
I can only agree, but only so far as it’s a code smell. However, it has nothing to
do with DI in general or &lt;strong&gt;Constructor Injection&lt;/strong&gt; specifically. Rather,
it’s a smell that indicates a violation of the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt; (SRP). Let’s review the example constructor:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IAccountsReceivable\cf0  receivable,\par ??                      \cf4 IRateExchange\cf0  exchange,\par ??                      \cf4 IUserContext\cf0  userContext)}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; OrderProcessor(&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt; validator,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt; shipper,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IAccountsReceivable&lt;/span&gt; receivable,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IRateExchange&lt;/span&gt; exchange,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IUserContext&lt;/span&gt; userContext)&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In this version, I even added IOrderShipper back in &lt;a href="http://blog.ploeh.dk/2010/01/20/RebuttalConstructorOverinjectionAntipattern.aspx"&gt;as
I described in my earlier post&lt;/a&gt;. Surely, five constructor parameters are too many.
&lt;/p&gt;
&lt;p&gt;
&lt;em&gt;&lt;strong&gt;Constructor Injection&lt;/strong&gt; makes SRP violations glaringly obvious.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
What’s not to like? My personal threshold lies somewhere around 3-4 constructor parameters,
so whenever I hit three, I start to consider if I could perhaps aggregate some of
the dependencies into a new type.
&lt;/p&gt;
&lt;p&gt;
I call such a type an &lt;strong&gt;Aggregate Service&lt;/strong&gt;. It’s closely related to &lt;a href="http://www.refactoring.com/catalog/introduceParameterObject.html"&gt;Parameter
Objects&lt;/a&gt;, but the main difference is that a &lt;strong&gt;Parameter Object&lt;/strong&gt; only
moves the parameters to a common root, while an &lt;strong&gt;Aggregate Service&lt;/strong&gt; hides
the aggregate behavior behind a new abstraction. While the &lt;strong&gt;Aggregate Service&lt;/strong&gt; may
start its life as a result of a pure mechanistic refactoring, it often turns out that
the extracted behavior represents a Domain Concept in its own right. Congratulations:
you’ve just move a little closer to adhering to the SRP!
&lt;/p&gt;
&lt;p&gt;
Let’s look at Jeffrey Palermo’s OrderProcessor example. The core implementation of
the class is reproduced here (recall that in my version, IOrderShipper is also an
injected dependency):
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf4 SuccessResult\cf0  Process(\cf4 Order\cf0  order)\par ??\{\par ??    \cf1 bool\cf0  isValid = _validator.Validate(order);\par ??    \cf1 if\cf0  (isValid)\par ??    \{\par ??        Collect(order);\par ??        _shipper.Ship(order);\par ??    \}\par ??\par ??    \cf1 return\cf0  CreateStatus(isValid);\par ??\}\par ??\par ??\cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??    \cf4 Price\cf0  price = order.GetPrice(_exchange, _userContext);\par ??    _receivable.Collect(user, price);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: #2b91af"&gt;SuccessResult&lt;/span&gt; Process(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;bool&lt;/span&gt; isValid
= _validator.Validate(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (isValid)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; Collect(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _shipper.Ship(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; CreateStatus(isValid);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;User&lt;/span&gt; user
= _userContext.GetCurrentUser();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Price&lt;/span&gt; price
= order.GetPrice(_exchange, _userContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; _receivable.Collect(user, price);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
If you examine the code it should quickly become apparent that the Collect method
encapsulates a cluster of dependencies: IAccountsReceivable, IRateExchange and IUserContext.
In this case it’s pretty obvious because they are already encapsulated in a single
private method. In real production code, you may need to perform a series of internal
refactorings before a pattern starts to emerge and you can extract an interface that
aggregates several dependencies.
&lt;/p&gt;
&lt;p&gt;
Now that we have identified the cluster of dependencies, we can extract an interface
that closely resembles the Collect method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 interface\cf0  \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 void\cf0  Collect(\cf4 Order\cf0  order);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;interface&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
In lieu of a better name, I simply chose to call it IOrderCollector, but what’s interesting
about extracting &lt;strong&gt;Aggregate Services&lt;/strong&gt; is that over time, they often
turn out to be previously &lt;em&gt;implicit&lt;/em&gt; Domain Concepts that we have now dragged
out in the open and made &lt;em&gt;explicit&lt;/em&gt;.
&lt;/p&gt;
&lt;p&gt;
We can now inject IOrderCollector into OrderProcessor and change the implementation
of the private Collect method:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 private\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??\{\par ??    _collector.Collect(order);\par ??\}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; _collector.Collect(order);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Next, we can remove the redundant dependencies, leaving us with this constructor:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  OrderProcessor(\cf4 IOrderValidator\cf0  validator,\par ??                      \cf4 IOrderShipper\cf0  shipper,\par ??                      \cf4 IOrderCollector\cf0  collector)}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; OrderProcessor(&lt;span style="color: #2b91af"&gt;IOrderValidator&lt;/span&gt; validator,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IOrderShipper&lt;/span&gt; shipper,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt; collector)&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
With three constructor parameters it’s much more acceptable, but we can always consider
repeating the procedure and extract a new &lt;strong&gt;Aggregate Service&lt;/strong&gt; that
aggregates IOrderShipper and IOrderCollector.
&lt;/p&gt;
&lt;p&gt;
The original behavior from the Collect method is still required, but is now implemented
in the OrderCollector class:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 OrderCollector\cf0  : \cf4 IOrderCollector\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IUserContext\cf0  _userContext;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IRateExchange\cf0  _exchange;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IAccountsReceivable\cf0  _receivable;\par ??\par ??    \cf1 public\cf0  OrderCollector(\cf4 IAccountsReceivable\cf0  receivable,\par ??                          \cf4 IRateExchange\cf0  exchange,\par ??                          \cf4 IUserContext\cf0  userContext)\par ??    \{\par ??        _receivable = receivable;\par ??        _exchange = exchange;\par ??        _userContext = userContext;\par ??    \}\par ??\par ??\cf1     #region\cf0  IOrderCollector Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  Collect(\cf4 Order\cf0  order)\par ??    \{\par ??        \cf4 User\cf0  user = _userContext.GetCurrentUser();\par ??        \cf4 Price\cf0  price = \par ??            order.GetPrice(_exchange, _userContext);\par ??        _receivable.Collect(user, price);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;OrderCollector&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IOrderCollector&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IUserContext&lt;/span&gt; _userContext;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IRateExchange&lt;/span&gt; _exchange;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IAccountsReceivable&lt;/span&gt; _receivable;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; OrderCollector(&lt;span style="color: #2b91af"&gt;IAccountsReceivable&lt;/span&gt; receivable,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IRateExchange&lt;/span&gt; exchange,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IUserContext&lt;/span&gt; userContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _receivable = receivable;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _exchange = exchange;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _userContext = userContext;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IOrderCollector Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Collect(&lt;span style="color: #2b91af"&gt;Order&lt;/span&gt; order)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;User&lt;/span&gt; user
= _userContext.GetCurrentUser();&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Price&lt;/span&gt; price
= &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; order.GetPrice(_exchange, _userContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; _receivable.Collect(user, price);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Here’s another class with three constructor parameters, which falls within the reasonable
range. However, once again, we can begin to consider whether the interaction between
IUserContext and the Order could be better modeled.
&lt;/p&gt;
&lt;p&gt;
In outline form, the &lt;em&gt;Introduce Aggregate Service&lt;/em&gt; refactoring follows these
steps:
&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;
Analyze how dependencies interact to identify clusters of behavior. 
&lt;li&gt;
Extract an interface from these clusters. 
&lt;li&gt;
Copy the original implementation to a class that implements the new interface. 
&lt;li&gt;
Inject the new interface into the consumer. 
&lt;li&gt;
Replace the original implementation with a call the new dependency. 
&lt;li&gt;
Remove the redundant dependencies. 
&lt;li&gt;
Rinse and repeat :)&lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;
The beauty of &lt;strong&gt;Aggregate Services&lt;/strong&gt; is that we can keep wrapping one &lt;strong&gt;Aggregate
Service&lt;/strong&gt; in new &lt;strong&gt;Aggregate Services&lt;/strong&gt; to define more and more
coarse-grained building blocks as we get closer and closer to the application boundary.
&lt;/p&gt;
&lt;p&gt;
Keeping each class and its dependencies to simple interactions also makes it much
easier to unit test all of them because none of them do anything particularly complex.
&lt;/p&gt;
&lt;p&gt;
Adhering strictly to &lt;strong&gt;Constructor Injection&lt;/strong&gt; makes it easy to see when
one violates the SRP and should refactor to an &lt;strong&gt;Aggregate Service&lt;/strong&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=85a3b4b6-f27b-4ad4-9415-fef6282c3dd5" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,85a3b4b6-f27b-4ad4-9415-fef6282c3dd5.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=7458672f-201e-47c5-a203-593520b55b45</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=7458672f-201e-47c5-a203-593520b55b45</wfw:commentRss>
      <slash:comments>3</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a reaction to <a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings">Uncle
Bob</a>'s recent post on <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion">Dependency
Injection Inversion</a>, <a href="http://blog.cgdecker.com/">Colin Decker</a> writes
that he <a href="http://blog.cgdecker.com/2010/01/whats-issue-with-inject.html">doesn't
consider the use of the single Guice @Inject annotation particularly problematic</a>.
As I read it, the central argument is that
</p>
        <blockquote>
          <p>
annotations are not code. By themselves, they do nothing.
</p>
        </blockquote>
        <p>
I'll have to take that at face value, but if we translate this reasoning to .NET it
certainly holds true. Attributes don't do anything by themselves.
</p>
        <p>
I'm not aware of any DI Container for .NET that <em>requires</em> us to sprinkle attributes
all over our code to work (I don't consider <a href="http://mef.codeplex.com/">MEF</a> a
DI Container), but for the sake of argument, let's assume that such a container exists
(let's call it <em><a href="http://en.wikipedia.org/wiki/Hypodermic_needle">Needle</a></em>).
Would it be so bad if we had to liberally apply the Needle [Inject] attribute in large
parts of our code bases?
</p>
        <p>
Colin suggests <em>no</em>. As usual, my position is that it depends, but in most
cases I would consider it bad.
</p>
        <p>
If Needle is implemented like most libraries, InjectAttribute is just one of many
types that make up the entire API. Other types would include NeedleContainer and its
associated classes.
</p>
        <p>
Java annotations may work differently, but in .NET we need to reference a library
to apply one of its attributes. To apply the [Inject] attribute, we would have to
reference Needle, and herein lies the problem.
</p>
        <p>
Once Needle is referenced, it becomes much easier for a junior developer to accidentally
start directly using other parts of the Needle API. Particularly he or she may start
using Needle as a Service Locator. When that happens, Needle is no longer a passive
participant of the code, but a very active one, and it becomes much harder to separate
the code from the Container.
</p>
        <p>
To paraphrase Uncle Bob: <em>I don't want to write a Needle application.</em></p>
        <p>
We can't even protect ourselves from accidental usage by writing a <a href="http://blogs.msdn.com/gblock/archive/2008/05/05/prismshouldnotreferenceunity.aspx">convention-based
unit test</a> that fails if Needle is referenced by our code, because it <em>must</em> be
referenced for the [Inject] attribute to be applied.
</p>
        <p>
The point is that the attribute drags in a reference to the entire container, which
in my opinion is a bad thing.
</p>
        <p>
So when would it be less problematic?
</p>
        <p>
If Needle was implemented in such a way that InjectAttribute was defined in an assembly
that only contains that one type, and the rest of Needle was implemented in a different
assembly, the attribute wouldn't drag the rest of the container along.
</p>
        <p>
Whether this whole analysis makes sense at all in Java, and whether Guice is implemented
like that, I can't say, but in most cases I would consider even a single attribute
to be unacceptable pollution of my code base.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7458672f-201e-47c5-a203-593520b55b45" />
      </body>
      <title>What's so dangerous about a DI attribute?</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/27/WhatsSoDangerousAboutADIAttribute.aspx</link>
      <pubDate>Wed, 27 Jan 2010 19:36:34 GMT</pubDate>
      <description>&lt;p&gt;
In a reaction to &lt;a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings"&gt;Uncle
Bob&lt;/a&gt;'s recent post on &lt;a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion"&gt;Dependency
Injection Inversion&lt;/a&gt;, &lt;a href="http://blog.cgdecker.com/"&gt;Colin Decker&lt;/a&gt; writes
that he &lt;a href="http://blog.cgdecker.com/2010/01/whats-issue-with-inject.html"&gt;doesn't
consider the use of the single Guice @Inject annotation particularly problematic&lt;/a&gt;.
As I read it, the central argument is that
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
annotations are not code. By themselves, they do nothing.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
I'll have to take that at face value, but if we translate this reasoning to .NET it
certainly holds true. Attributes don't do anything by themselves.
&lt;/p&gt;
&lt;p&gt;
I'm not aware of any DI Container for .NET that &lt;em&gt;requires&lt;/em&gt; us to sprinkle attributes
all over our code to work (I don't consider &lt;a href="http://mef.codeplex.com/"&gt;MEF&lt;/a&gt; a
DI Container), but for the sake of argument, let's assume that such a container exists
(let's call it &lt;em&gt;&lt;a href="http://en.wikipedia.org/wiki/Hypodermic_needle"&gt;Needle&lt;/a&gt;&lt;/em&gt;).
Would it be so bad if we had to liberally apply the Needle [Inject] attribute in large
parts of our code bases?
&lt;/p&gt;
&lt;p&gt;
Colin suggests &lt;em&gt;no&lt;/em&gt;. As usual, my position is that it depends, but in most
cases I would consider it bad.
&lt;/p&gt;
&lt;p&gt;
If Needle is implemented like most libraries, InjectAttribute is just one of many
types that make up the entire API. Other types would include NeedleContainer and its
associated classes.
&lt;/p&gt;
&lt;p&gt;
Java annotations may work differently, but in .NET we need to reference a library
to apply one of its attributes. To apply the [Inject] attribute, we would have to
reference Needle, and herein lies the problem.
&lt;/p&gt;
&lt;p&gt;
Once Needle is referenced, it becomes much easier for a junior developer to accidentally
start directly using other parts of the Needle API. Particularly he or she may start
using Needle as a Service Locator. When that happens, Needle is no longer a passive
participant of the code, but a very active one, and it becomes much harder to separate
the code from the Container.
&lt;/p&gt;
&lt;p&gt;
To paraphrase Uncle Bob: &lt;em&gt;I don't want to write a Needle application.&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
We can't even protect ourselves from accidental usage by writing a &lt;a href="http://blogs.msdn.com/gblock/archive/2008/05/05/prismshouldnotreferenceunity.aspx"&gt;convention-based
unit test&lt;/a&gt; that fails if Needle is referenced by our code, because it &lt;em&gt;must&lt;/em&gt; be
referenced for the [Inject] attribute to be applied.
&lt;/p&gt;
&lt;p&gt;
The point is that the attribute drags in a reference to the entire container, which
in my opinion is a bad thing.
&lt;/p&gt;
&lt;p&gt;
So when would it be less problematic?
&lt;/p&gt;
&lt;p&gt;
If Needle was implemented in such a way that InjectAttribute was defined in an assembly
that only contains that one type, and the rest of Needle was implemented in a different
assembly, the attribute wouldn't drag the rest of the container along.
&lt;/p&gt;
&lt;p&gt;
Whether this whole analysis makes sense at all in Java, and whether Guice is implemented
like that, I can't say, but in most cases I would consider even a single attribute
to be unacceptable pollution of my code base.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=7458672f-201e-47c5-a203-593520b55b45" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,7458672f-201e-47c5-a203-593520b55b45.aspx</comments>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=2aef793d-f3f4-479f-9144-b26e093f8376</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=2aef793d-f3f4-479f-9144-b26e093f8376</wfw:commentRss>
      <slash:comments>7</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
Reacting to my <a href="http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx">previous
post</a>, <a href="http://kozmic.pl/Default.aspx">Krzysztof Koźmic</a> was so kind
to point out to me that I really should be using an IWindsorInstaller instead of writing
the registration code in a static helper method (it <em>did</em> make me cringe a
bit).
</p>
        <p>
As it turns out, IWindsorInstaller is not a particularly well-described feature of <a href="http://castleproject.org/container/index.html">Castle
Windsor</a>, so here's a quick introduction. Fortunately, it is very easy to understand.
</p>
        <p>
The idea is simply to package configuration code in reusable modules (just like the
Guice modules from <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion">Uncle
Bob's post</a>).
</p>
        <p>
Refactoring the bootstrap code from my previous post, I can now move all the container
configuration code into a reusable module:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">BillingContainerInstaller</span> : <span style="color: #2b91af">IWindsorInstaller</span></p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
            <span style="color: blue">    #region</span> IWindsorInstaller Members
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span><span style="color: blue">void</span> Install(<span style="color: #2b91af">IWindsorContainer</span> container,
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">IConfigurationStore</span> store)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        container.AddComponent&lt;<span style="color: #2b91af">TransactionLog</span>, 
</p>
          <p style="margin: 0px">
            <span style="color: #2b91af">DatabaseTransactionLog</span>&gt;();
</p>
          <p style="margin: 0px">
        container.AddComponent&lt;<span style="color: #2b91af">CreditCardProcessor</span>,
</p>
          <p style="margin: 0px">
            <span style="color: #2b91af">MyCreditCardProcessor</span>&gt;();
</p>
          <p style="margin: 0px">
        container.AddComponent&lt;<span style="color: #2b91af">BillingService</span>&gt;();
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
            <span style="color: blue">    #endregion</span>
          </p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
While I was at it, I also changed from the fluent registration API to the generic
registration methods as I didn't really need the full API, but I could have left it
as it was.
</p>
        <p>
BillingContainerInstaller implements IWindsorInstaller, and I can now configure my
container instance like this:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">var</span> container = <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();
</p>
          <p style="margin: 0px">
container.Install(<span style="color: blue">new</span><span style="color: #2b91af">BillingContainerInstaller</span>());
</p>
        </div>
        <p>
The Install method takes a parameter array of IWindsorInstaller instances, so you
can pass as many as you'd like.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2aef793d-f3f4-479f-9144-b26e093f8376" />
      </body>
      <title>IWindsorInstaller</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/26/IWindsorInstaller.aspx</link>
      <pubDate>Tue, 26 Jan 2010 19:24:51 GMT</pubDate>
      <description>&lt;p&gt;
Reacting to my &lt;a href="http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx"&gt;previous
post&lt;/a&gt;, &lt;a href="http://kozmic.pl/Default.aspx"&gt;Krzysztof Koźmic&lt;/a&gt; was so kind
to point out to me that I really should be using an IWindsorInstaller instead of writing
the registration code in a static helper method (it &lt;em&gt;did&lt;/em&gt; make me cringe a
bit).
&lt;/p&gt;
&lt;p&gt;
As it turns out, IWindsorInstaller is not a particularly well-described feature of &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt;, so here's a quick introduction. Fortunately, it is very easy to understand.
&lt;/p&gt;
&lt;p&gt;
The idea is simply to package configuration code in reusable modules (just like the
Guice modules from &lt;a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion"&gt;Uncle
Bob's post&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
Refactoring the bootstrap code from my previous post, I can now move all the container
configuration code into a reusable module:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;BillingContainerInstaller&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IWindsorInstaller&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #region&lt;/span&gt; IWindsorInstaller Members
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Install(&lt;span style="color: #2b91af"&gt;IWindsorContainer&lt;/span&gt; container,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;IConfigurationStore&lt;/span&gt; store)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddComponent&amp;lt;&lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt;, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;DatabaseTransactionLog&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddComponent&amp;lt;&lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt;,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;MyCreditCardProcessor&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.AddComponent&amp;lt;&lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; #endregion&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
While I was at it, I also changed from the fluent registration API to the generic
registration methods as I didn't really need the full API, but I could have left it
as it was.
&lt;/p&gt;
&lt;p&gt;
BillingContainerInstaller implements IWindsorInstaller, and I can now configure my
container instance like this:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;var&lt;/span&gt; container = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
container.Install(&lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;BillingContainerInstaller&lt;/span&gt;());
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
The Install method takes a parameter array of IWindsorInstaller instances, so you
can pass as many as you'd like.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=2aef793d-f3f4-479f-9144-b26e093f8376" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,2aef793d-f3f4-479f-9144-b26e093f8376.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=224fbfca-7f4a-4d5c-a713-8db5e0720fe2</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=224fbfca-7f4a-4d5c-a713-8db5e0720fe2</wfw:commentRss>
      <slash:comments>5</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
About a week ago <a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings">Uncle
Bob</a> published a post on <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion">Dependency
Injection Inversion</a> that caused quite a stir in the tiny part of the .NET community
I usually pretend to hang out with. Twitter was alive with much debate, but <a href="http://ayende.com/Blog/Default.aspx">Ayende</a> seems
to <a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx">sum
up</a> the .NET DI community's sentiment pretty well:
</p>
        <blockquote>
          <p>
if this is a typical example of IoC usage in the Java world, then [Uncle Bob] should
peek over the fence to see how IoC is commonly implemented in the .Net space
</p>
        </blockquote>
        <p>
Despite having initially left a more or less positive note to Uncle Bob's post, after
having re-read it carefully, I am beginning to think the same, but instead of just <em>telling</em> everyone
how much greener the grass is on the .NET side, let me <em>show</em> you.
</p>
        <p>
First of all, let's translate Uncle Bob's BillingService to C#:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">BillingService</span>
          </p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">CreditCardProcessor</span> processor;
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">TransactionLog</span> transactionLog;
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span> BillingService(<span style="color: #2b91af">CreditCardProcessor</span> processor,
</p>
          <p style="margin: 0px">
        <span style="color: #2b91af">TransactionLog</span> transactionLog)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (processor
== <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"processor"</span>);
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
        <span style="color: blue">if</span> (transactionLog
== <span style="color: blue">null</span>)
</p>
          <p style="margin: 0px">
        {
</p>
          <p style="margin: 0px">
            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"transactionLog"</span>);
</p>
          <p style="margin: 0px">
        }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.processor
= processor;
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.transactionLog
= transactionLog;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">public</span><span style="color: blue">void</span> ProcessCharge(<span style="color: blue">int</span> amount, <span style="color: blue">string</span> id)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">var</span> approval
= <span style="color: blue">this</span>.processor.Approve(amount, id);
</p>
          <p style="margin: 0px">
        <span style="color: blue">this</span>.transactionLog.Log(<span style="color: blue">string</span>.Format(
</p>
          <p style="margin: 0px">
            <span style="color: #a31515">"Transaction
by {0} for {1} {2}"</span>, id, amount, 
</p>
          <p style="margin: 0px">
            <span style="color: blue">this</span>.GetApprovalCode(approval)));
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">private</span><span style="color: blue">string</span> GetApprovalCode(<span style="color: blue">bool</span> approval)
</p>
          <p style="margin: 0px">
    {
</p>
          <p style="margin: 0px">
        <span style="color: blue">return</span> approval
? <span style="color: #a31515">"approved"</span> : <span style="color: #a31515">"denied"</span>;
</p>
          <p style="margin: 0px">
    }
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
It's nice how easy it is to translate Java code to C#, but apart from casing and other
minor deviations, let's focus on the main difference. I've added Guard Clauses to
protect the injected dependencies against null values as I consider this an essential
and required part of <strong>Constructor Injection</strong> – I think Uncle Bob should
have added those as well, but he might have omitted them for brevity.
</p>
        <p>
If you disregard the Guard Clauses, the C# version is a logical line of code shorter
than the Java version because it has no DI attribute like Guice's @Inject.
</p>
        <p>
Does this mean that we can't do DI with the C# version of BillingService? Uncle Bob
seems to imply that we can do <em>Dependency Inversion</em>, but not <em>Dependency
Injection</em> - or is it the other way around? I can't really make head or tails
of that part of the post…
</p>
        <p>
The interesting part is that in .NET, <em>there's no difference!</em> We can use DI
Containers with the BillingService without sprinkling DI attributes all over our code
base. The BillingService class has no reference to any DI Container.
</p>
        <p>
It does, however, use the central DI pattern <strong>Constructor Injection</strong>.
.NET DI Containers know all about this pattern, and with .NET's static type system
they know all they need to know to wire dependencies up correctly. (I thought that
Java had a static type system as well, but perhaps I am mistaken.) The .NET DI Containers
will figure it out for you – you don't have to explicitly tell them how to invoke
a constructor with two parameters.
</p>
        <p>
We can write an entire application by using <strong>Constructor Injection</strong> and
stacking dependencies <em>without ever referencing a container!</em></p>
        <p>
Like the Lean concept of the <em>Last Responsible Moment</em>, we can wait until the
application's entry point to decide how we will wire up the dependencies.
</p>
        <p>
As Uncle Bob suggests, we can use <strong>Poor Man's DI</strong> and manually create
the dependencies directly in Main, but as <a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx">Ayende
correctly observes</a>, that only looks like an attractive alternative because the
example is so simple. For complex dependency graphs, a DI Container is a much better
choice.
</p>
        <p>
With the C# version of BillingService, which DI Container must we select?
</p>
        <p>
It doesn't matter: we can choose whichever one we would like because we have been
following patterns instead of using a framework.
</p>
        <p>
Here's an example of an implementation of Main using <a href="http://castleproject.org/">Castle
Windsor</a>:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Main(<span style="color: blue">string</span>[]
args)
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> container = <span style="color: blue">new</span><span style="color: #2b91af">WindsorContainer</span>();
</p>
          <p style="margin: 0px">
    <span style="color: #2b91af">Program</span>.Configure(container);
</p>
          <p style="margin: 0px">
 
</p>
          <p style="margin: 0px">
    <span style="color: blue">var</span> billingService =
</p>
          <p style="margin: 0px">
        container.Resolve&lt;<span style="color: #2b91af">BillingService</span>&gt;();
</p>
          <p style="margin: 0px">
    billingService.ProcessCharge(<span style="color: #a52a2a">2034</span>, <span style="color: #a31515">"Bob"</span>);
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
This looks a lot like Uncle Bob's first Guice example, but instead of injecting a
BillingModule into the container, we can configure it inline or in a helper method:
</p>
        <div style="font-family: consolas; background: white; color: black; font-size: 10pt">
          <p style="margin: 0px">
            <span style="color: blue">private</span>
            <span style="color: blue">static</span>
            <span style="color: blue">void</span> Configure(<span style="color: #2b91af">WindsorContainer</span> container)
</p>
          <p style="margin: 0px">
{
</p>
          <p style="margin: 0px">
    container.Register(<span style="color: #2b91af">Component</span></p>
          <p style="margin: 0px">
        .For&lt;<span style="color: #2b91af">TransactionLog</span>&gt;()
</p>
          <p style="margin: 0px">
        .ImplementedBy&lt;<span style="color: #2b91af">DatabaseTransactionLog</span>&gt;());
</p>
          <p style="margin: 0px">
    container.Register(<span style="color: #2b91af">Component</span></p>
          <p style="margin: 0px">
        .For&lt;<span style="color: #2b91af">CreditCardProcessor</span>&gt;()
</p>
          <p style="margin: 0px">
        .ImplementedBy&lt;<span style="color: #2b91af">MyCreditCardProcessor</span>&gt;());
</p>
          <p style="margin: 0px">
    container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">BillingService</span>&gt;());
</p>
          <p style="margin: 0px">
}
</p>
        </div>
        <p>
This corresponds more or less to the Guice-specific BillingModule, although Windsor
also requires us to register the concrete BillingService as a component (this last
step varies a bit from DI Container to DI Container – it is, for example, redundant
in <a href="http://www.codeplex.com/unity">Unity</a>).
</p>
        <p>
Imagine that in the future we want to rewire this program to use a different DI Container.
The only piece of code we need to change is this <strong>Composition Root</strong>.
We need to change the container declaration and configuration and then we are ready
to use a different DI Container.
</p>
        <p>
The bottom line is that Uncle Bob's <em>Dependency Injection Inversion</em> is redundant
in .NET. Just use a few well-known design patterns and principles and you can write
entire applications with DI-friendly, DI-agnostic code bases.
</p>
        <p>
I recently posted a <a href="http://stackoverflow.com/questions/2045904/dependency-inject-di-friendly-library/2047657#2047657">first
take on guidelines for writing DI-agnostic code</a>. I plan to evolve these guiding
principles and make them a part of <a href="http://www.manning.com/seemann">my upcoming
book</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=224fbfca-7f4a-4d5c-a713-8db5e0720fe2" />
      </body>
      <title>Dependency Injection Inversion in .NET</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</guid>
      <link>http://blog.ploeh.dk/2010/01/25/DependencyInjectionInversionInNET.aspx</link>
      <pubDate>Mon, 25 Jan 2010 20:48:27 GMT</pubDate>
      <description>&lt;p&gt;
About a week ago &lt;a href="http://blog.objectmentor.com/articles/category/uncle-bobs-blatherings"&gt;Uncle
Bob&lt;/a&gt; published a post on &lt;a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion"&gt;Dependency
Injection Inversion&lt;/a&gt; that caused quite a stir in the tiny part of the .NET community
I usually pretend to hang out with. Twitter was alive with much debate, but &lt;a href="http://ayende.com/Blog/Default.aspx"&gt;Ayende&lt;/a&gt; seems
to &lt;a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx"&gt;sum
up&lt;/a&gt; the .NET DI community's sentiment pretty well:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
if this is a typical example of IoC usage in the Java world, then [Uncle Bob] should
peek over the fence to see how IoC is commonly implemented in the .Net space
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Despite having initially left a more or less positive note to Uncle Bob's post, after
having re-read it carefully, I am beginning to think the same, but instead of just &lt;em&gt;telling&lt;/em&gt; everyone
how much greener the grass is on the .NET side, let me &lt;em&gt;show&lt;/em&gt; you.
&lt;/p&gt;
&lt;p&gt;
First of all, let's translate Uncle Bob's BillingService to C#:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt; processor;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt; transactionLog;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; BillingService(&lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt; processor,
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt; transactionLog)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (processor
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"processor"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (transactionLog
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"transactionLog"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.processor
= processor;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.transactionLog
= transactionLog;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; ProcessCharge(&lt;span style="color: blue"&gt;int&lt;/span&gt; amount, &lt;span style="color: blue"&gt;string&lt;/span&gt; id)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; approval
= &lt;span style="color: blue"&gt;this&lt;/span&gt;.processor.Approve(amount, id);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.transactionLog.Log(&lt;span style="color: blue"&gt;string&lt;/span&gt;.Format(
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #a31515"&gt;"Transaction
by {0} for {1} {2}"&lt;/span&gt;, id, amount, 
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.GetApprovalCode(approval)));
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;string&lt;/span&gt; GetApprovalCode(&lt;span style="color: blue"&gt;bool&lt;/span&gt; approval)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; {
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;return&lt;/span&gt; approval
? &lt;span style="color: #a31515"&gt;"approved"&lt;/span&gt; : &lt;span style="color: #a31515"&gt;"denied"&lt;/span&gt;;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; }
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
It's nice how easy it is to translate Java code to C#, but apart from casing and other
minor deviations, let's focus on the main difference. I've added Guard Clauses to
protect the injected dependencies against null values as I consider this an essential
and required part of &lt;strong&gt;Constructor Injection&lt;/strong&gt; – I think Uncle Bob should
have added those as well, but he might have omitted them for brevity.
&lt;/p&gt;
&lt;p&gt;
If you disregard the Guard Clauses, the C# version is a logical line of code shorter
than the Java version because it has no DI attribute like Guice's @Inject.
&lt;/p&gt;
&lt;p&gt;
Does this mean that we can't do DI with the C# version of BillingService? Uncle Bob
seems to imply that we can do &lt;em&gt;Dependency Inversion&lt;/em&gt;, but not &lt;em&gt;Dependency
Injection&lt;/em&gt; - or is it the other way around? I can't really make head or tails
of that part of the post…
&lt;/p&gt;
&lt;p&gt;
The interesting part is that in .NET, &lt;em&gt;there's no difference!&lt;/em&gt; We can use DI
Containers with the BillingService without sprinkling DI attributes all over our code
base. The BillingService class has no reference to any DI Container.
&lt;/p&gt;
&lt;p&gt;
It does, however, use the central DI pattern &lt;strong&gt;Constructor Injection&lt;/strong&gt;.
.NET DI Containers know all about this pattern, and with .NET's static type system
they know all they need to know to wire dependencies up correctly. (I thought that
Java had a static type system as well, but perhaps I am mistaken.) The .NET DI Containers
will figure it out for you – you don't have to explicitly tell them how to invoke
a constructor with two parameters.
&lt;/p&gt;
&lt;p&gt;
We can write an entire application by using &lt;strong&gt;Constructor Injection&lt;/strong&gt; and
stacking dependencies &lt;em&gt;without ever referencing a container!&lt;/em&gt;
&lt;/p&gt;
&lt;p&gt;
Like the Lean concept of the &lt;em&gt;Last Responsible Moment&lt;/em&gt;, we can wait until the
application's entry point to decide how we will wire up the dependencies.
&lt;/p&gt;
&lt;p&gt;
As Uncle Bob suggests, we can use &lt;strong&gt;Poor Man's DI&lt;/strong&gt; and manually create
the dependencies directly in Main, but as &lt;a href="http://ayende.com/Blog/archive/2010/01/22/rejecting-dependency-injection-inversion.aspx"&gt;Ayende
correctly observes&lt;/a&gt;, that only looks like an attractive alternative because the
example is so simple. For complex dependency graphs, a DI Container is a much better
choice.
&lt;/p&gt;
&lt;p&gt;
With the C# version of BillingService, which DI Container must we select?
&lt;/p&gt;
&lt;p&gt;
It doesn't matter: we can choose whichever one we would like because we have been
following patterns instead of using a framework.
&lt;/p&gt;
&lt;p&gt;
Here's an example of an implementation of Main using &lt;a href="http://castleproject.org/"&gt;Castle
Windsor&lt;/a&gt;:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Main(&lt;span style="color: blue"&gt;string&lt;/span&gt;[]
args)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; container = &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;Program&lt;/span&gt;.Configure(container);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;var&lt;/span&gt; billingService =
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Resolve&amp;lt;&lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;&amp;gt;();
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; billingService.ProcessCharge(&lt;span style="color: #a52a2a"&gt;2034&lt;/span&gt;, &lt;span style="color: #a31515"&gt;"Bob"&lt;/span&gt;);
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
This looks a lot like Uncle Bob's first Guice example, but instead of injecting a
BillingModule into the container, we can configure it inline or in a helper method:
&lt;/p&gt;
&lt;div style="font-family: consolas; background: white; color: black; font-size: 10pt"&gt;
&lt;p style="margin: 0px"&gt;
&lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;static&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Configure(&lt;span style="color: #2b91af"&gt;WindsorContainer&lt;/span&gt; container)
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
{
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;TransactionLog&lt;/span&gt;&amp;gt;()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;DatabaseTransactionLog&lt;/span&gt;&amp;gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .For&amp;lt;&lt;span style="color: #2b91af"&gt;CreditCardProcessor&lt;/span&gt;&amp;gt;()
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;MyCreditCardProcessor&lt;/span&gt;&amp;gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
&amp;nbsp;&amp;nbsp;&amp;nbsp; container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;BillingService&lt;/span&gt;&amp;gt;());
&lt;/p&gt;
&lt;p style="margin: 0px"&gt;
}
&lt;/p&gt;
&lt;/div&gt;
&lt;p&gt;
This corresponds more or less to the Guice-specific BillingModule, although Windsor
also requires us to register the concrete BillingService as a component (this last
step varies a bit from DI Container to DI Container – it is, for example, redundant
in &lt;a href="http://www.codeplex.com/unity"&gt;Unity&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
Imagine that in the future we want to rewire this program to use a different DI Container.
The only piece of code we need to change is this &lt;strong&gt;Composition Root&lt;/strong&gt;.
We need to change the container declaration and configuration and then we are ready
to use a different DI Container.
&lt;/p&gt;
&lt;p&gt;
The bottom line is that Uncle Bob's &lt;em&gt;Dependency Injection Inversion&lt;/em&gt; is redundant
in .NET. Just use a few well-known design patterns and principles and you can write
entire applications with DI-friendly, DI-agnostic code bases.
&lt;/p&gt;
&lt;p&gt;
I recently posted a &lt;a href="http://stackoverflow.com/questions/2045904/dependency-inject-di-friendly-library/2047657#2047657"&gt;first
take on guidelines for writing DI-agnostic code&lt;/a&gt;. I plan to evolve these guiding
principles and make them a part of &lt;a href="http://www.manning.com/seemann"&gt;my upcoming
book&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=224fbfca-7f4a-4d5c-a713-8db5e0720fe2" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,224fbfca-7f4a-4d5c-a713-8db5e0720fe2.aspx</comments>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
      <category>Software Design</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=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=8a17892b-9977-4899-82f7-277a105d156d</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=8a17892b-9977-4899-82f7-277a105d156d</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I'll be doing a TechTalk on the Managed Extensibility Framework and Dependency Injection
at Microsoft Denmark January 20th 2010.
</p>
        <p>
The talk will be in Danish. <a href="http://msdn.microsoft.com/da-dk/dd796175.aspx">Details
and sign-up here</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=8a17892b-9977-4899-82f7-277a105d156d" />
      </body>
      <title>MEF TechTalk with me</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/20/MEFTechTalkWithMe.aspx</link>
      <pubDate>Sun, 20 Dec 2009 19:56:33 GMT</pubDate>
      <description>&lt;p&gt;
I'll be doing a TechTalk on the Managed Extensibility Framework and Dependency Injection
at Microsoft Denmark January 20th 2010.
&lt;/p&gt;
&lt;p&gt;
The talk will be in Danish. &lt;a href="http://msdn.microsoft.com/da-dk/dd796175.aspx"&gt;Details
and sign-up here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=8a17892b-9977-4899-82f7-277a105d156d" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,8a17892b-9977-4899-82f7-277a105d156d.aspx</comments>
      <category>Dependency Injection</category>
      <category>Miscellaneous</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=ee8935b9-d418-4078-99e6-71eec380680b</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=ee8935b9-d418-4078-99e6-71eec380680b</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In my previous posts I discussed <a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx">how
to enable global error handling in ASP.NET MVC</a> and <a href="http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx">how
to inject a logging interface into the error handler</a>. In these posts, I simplified
things a bit to get my points across.
</p>
        <p>
In production we don't use a custom ErrorHandlingControllerFactory to configure all
Controllers with error handling, nor do we instantiate IExceptionFilters manually.
What I described was the Poor Man's Dependency Injection (DI) approach, which I find
most appropriate when describing DI concepts.
</p>
        <p>
However, we really use <a href="http://castleproject.org/container/index.html">Castle
Windsor</a> currently, so the wiring looks a bit different although it's still exactly
the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter
are any different than I have already described, but for completeness I wanted to
share a bit of our Windsor code.
</p>
        <p>
This is how we really wire our Controllers:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 container.Register(\cf3 AllTypes\par ??\cf0     .FromAssemblyContaining(representativeControllerType)\par ??    .BasedOn&lt;\cf3 Controller\cf0 &gt;()\par ??    .ConfigureFor&lt;\cf3 Controller\cf0 &gt;(reg =&gt; \par ??        reg.LifeStyle.PerWebRequest.ServiceOverrides(\par ??            \cf4 new\cf0  \{ ActionInvoker = \cf4 typeof\cf0 (\par ??                \cf3 ErrorHandlingControllerActionInvoker\cf0 )\par ??                .FullName \})));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">AllTypes</span></pre>
          <pre style="margin: 0px">    .FromAssemblyContaining(representativeControllerType)</pre>
          <pre style="margin: 0px">    .BasedOn&lt;<span style="color: #2b91af">Controller</span>&gt;()</pre>
          <pre style="margin: 0px">    .ConfigureFor&lt;<span style="color: #2b91af">Controller</span>&gt;(reg
=&gt; </pre>
          <pre style="margin: 0px">        reg.LifeStyle.PerWebRequest.ServiceOverrides(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span> {
ActionInvoker = <span style="color: blue">typeof</span>(</pre>
          <pre style="margin: 0px">                <span style="color: #2b91af">ErrorHandlingControllerActionInvoker</span>)</pre>
          <pre style="margin: 0px">                .FullName })));</pre>
        </div>
        <p>
Most of this statement simply instructs Windsor to scan all types in the specified
assembly for Controller implementations and register them. The interesting part is
the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining
that the ActionInvoker property should be wired up with an instance of the component
registered as ErrorHandlingControllerActionInvoker.
</p>
        <p>
Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance
we need to configure at least one of these as well. Instead of one, however, we have
two:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 container.Register(\cf3 Component\cf0 .For&lt;\cf3 IExceptionFilter\cf0 &gt;()\par ??    .ImplementedBy&lt;\cf3 LoggingExceptionFilter\cf0 &gt;());\par ??container.Register(\cf3 Component\cf0 .For&lt;\cf3 IExceptionFilter\cf0 &gt;()\par ??    .ImplementedBy&lt;\cf3 HandleErrorAttribute\cf0 &gt;());}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IExceptionFilter</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">LoggingExceptionFilter</span>&gt;());</pre>
          <pre style="margin: 0px">container.Register(<span style="color: #2b91af">Component</span>.For&lt;<span style="color: #2b91af">IExceptionFilter</span>&gt;()</pre>
          <pre style="margin: 0px">    .ImplementedBy&lt;<span style="color: #2b91af">HandleErrorAttribute</span>&gt;());</pre>
        </div>
        <p>
This is Windsor's elegant way of registering <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorators</a>:
you simply register the Decorator before the decorated type, and it'll Auto-Wire everything
for you.
</p>
        <p>
Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from
the <a href="http://www.codeplex.com/MVCContrib">MVC Contrib</a> project.
</p>
        <p>
To reiterate: You don't have to use Castle Windsor to enable global error handling
or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous
posts, or you can use some other DI Container. The purpose of this post was simply
to demonstrate one way to take it to the next level.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ee8935b9-d418-4078-99e6-71eec380680b" />
      </body>
      <title>Wiring ASP.NET MVC Error Handling with Castle Windsor</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/14/WiringASPNETMVCErrorHandlingWithCastleWindsor.aspx</link>
      <pubDate>Mon, 14 Dec 2009 06:59:32 GMT</pubDate>
      <description>&lt;p&gt;
In my previous posts I discussed &lt;a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx"&gt;how
to enable global error handling in ASP.NET MVC&lt;/a&gt; and &lt;a href="http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx"&gt;how
to inject a logging interface into the error handler&lt;/a&gt;. In these posts, I simplified
things a bit to get my points across.
&lt;/p&gt;
&lt;p&gt;
In production we don't use a custom ErrorHandlingControllerFactory to configure all
Controllers with error handling, nor do we instantiate IExceptionFilters manually.
What I described was the Poor Man's Dependency Injection (DI) approach, which I find
most appropriate when describing DI concepts.
&lt;/p&gt;
&lt;p&gt;
However, we really use &lt;a href="http://castleproject.org/container/index.html"&gt;Castle
Windsor&lt;/a&gt; currently, so the wiring looks a bit different although it's still exactly
the same thing that's going on. Neither ErrorHandlingActionInvoker nor LoggingExceptionFilter
are any different than I have already described, but for completeness I wanted to
share a bit of our Windsor code.
&lt;/p&gt;
&lt;p&gt;
This is how we really wire our Controllers:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;\red0\green0\blue255;}??\fs20 container.Register(\cf3 AllTypes\par ??\cf0     .FromAssemblyContaining(representativeControllerType)\par ??    .BasedOn&amp;lt;\cf3 Controller\cf0 &amp;gt;()\par ??    .ConfigureFor&amp;lt;\cf3 Controller\cf0 &amp;gt;(reg =&amp;gt; \par ??        reg.LifeStyle.PerWebRequest.ServiceOverrides(\par ??            \cf4 new\cf0  \{ ActionInvoker = \cf4 typeof\cf0 (\par ??                \cf3 ErrorHandlingControllerActionInvoker\cf0 )\par ??                .FullName \})));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;AllTypes&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .FromAssemblyContaining(representativeControllerType)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .BasedOn&amp;lt;&lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ConfigureFor&amp;lt;&lt;span style="color: #2b91af"&gt;Controller&lt;/span&gt;&amp;gt;(reg
=&amp;gt; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; reg.LifeStyle.PerWebRequest.ServiceOverrides(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; {
ActionInvoker = &lt;span style="color: blue"&gt;typeof&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerActionInvoker&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; .FullName })));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Most of this statement simply instructs Windsor to scan all types in the specified
assembly for Controller implementations and register them. The interesting part is
the ServiceOverrides method call that uses Windsor's rather excentric syntax for defining
that the ActionInvoker property should be wired up with an instance of the component
registered as ErrorHandlingControllerActionInvoker.
&lt;/p&gt;
&lt;p&gt;
Since ErrorHandlingControllerActionInvoker itself expects an IExceptionFilter instance
we need to configure at least one of these as well. Instead of one, however, we have
two:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red43\green145\blue175;}??\fs20 container.Register(\cf3 Component\cf0 .For&amp;lt;\cf3 IExceptionFilter\cf0 &amp;gt;()\par ??    .ImplementedBy&amp;lt;\cf3 LoggingExceptionFilter\cf0 &amp;gt;());\par ??container.Register(\cf3 Component\cf0 .For&amp;lt;\cf3 IExceptionFilter\cf0 &amp;gt;()\par ??    .ImplementedBy&amp;lt;\cf3 HandleErrorAttribute\cf0 &amp;gt;());}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt;&amp;gt;());&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;container.Register(&lt;span style="color: #2b91af"&gt;Component&lt;/span&gt;.For&amp;lt;&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&amp;gt;()&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; .ImplementedBy&amp;lt;&lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;&amp;gt;());&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is Windsor's elegant way of registering &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorators&lt;/a&gt;:
you simply register the Decorator before the decorated type, and it'll Auto-Wire everything
for you.
&lt;/p&gt;
&lt;p&gt;
Finally, we use a ControllerFactory very similar to the WindsorControllerFactory from
the &lt;a href="http://www.codeplex.com/MVCContrib"&gt;MVC Contrib&lt;/a&gt; project.
&lt;/p&gt;
&lt;p&gt;
To reiterate: You don't have to use Castle Windsor to enable global error handling
or logging in ASP.NET MVC. You can code it by hand as I've demonstrated in my previous
posts, or you can use some other DI Container. The purpose of this post was simply
to demonstrate one way to take it to the next level.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=ee8935b9-d418-4078-99e6-71eec380680b" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,ee8935b9-d418-4078-99e6-71eec380680b.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=be8504e1-b78f-4246-9338-717f7d0529b5</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=be8504e1-b78f-4246-9338-717f7d0529b5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
In a previous post I described <a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx">how
to enable global error handling in ASP.NET MVC applications</a>. Although I spent
some time talking about the importance of DRY, another major motivation for me was
to enable Dependency Injection (DI) with exception handling so that I could log stack
traces before letting ASP.NET MVC handle the exception.
</p>
        <p>
With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter
implementation. As an example I used HandleErrorAttribute, but obviously that doesn't
log anything. Once again, it would be tempting to derive from HandleErrorAttribute
and override its OnException method, but staying true to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single
Responsibility Principle</a> as well as the <a href="http://en.wikipedia.org/wiki/Open/closed_principle">Open/Closed
Principle</a> I rather prefer a <a href="http://en.wikipedia.org/wiki/Decorator_pattern">Decorator</a>:
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LoggingExceptionFilter\cf0  : \cf4 IExceptionFilter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IExceptionFilter\cf0  filter;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 ILogWriter\cf0  logWriter;\par ??\par ??    \cf1 public\cf0  LoggingExceptionFilter(\cf4 IExceptionFilter\cf0  filter,\par ??        \cf4 ILogWriter\cf0  logWriter)\par ??    \{\par ??        \cf1 if\cf0  (filter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "filter"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (logWriter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "logWriter"\cf0 );\par ??        \}        \par ??    \par ??        \cf1 this\cf0 .filter = filter;\par ??        \cf1 this\cf0 .logWriter = logWriter;\par ??    \}\par ??\par ??\cf1     #region\cf0  IExceptionFilter Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  OnException(\cf4 ExceptionContext\cf0  filterContext)\par ??    \{\par ??        \cf1 this\cf0 .logWriter.WriteError(filterContext.Exception);\par ??        \cf1 this\cf0 .filter.OnException(filterContext);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">
            <span style="color: blue">public</span>
            <span style="color: blue">class</span>
            <span style="color: #2b91af">LoggingExceptionFilter</span> : <span style="color: #2b91af">IExceptionFilter</span></pre>
          <pre style="margin: 0px">{</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">IExceptionFilter</span> filter;</pre>
          <pre style="margin: 0px">    <span style="color: blue">private</span><span style="color: blue">readonly</span><span style="color: #2b91af">ILogWriter</span> logWriter;</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span> LoggingExceptionFilter(<span style="color: #2b91af">IExceptionFilter</span> filter,</pre>
          <pre style="margin: 0px">        <span style="color: #2b91af">ILogWriter</span> logWriter)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (filter
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"filter"</span>);</pre>
          <pre style="margin: 0px">        }</pre>
          <pre style="margin: 0px">        <span style="color: blue">if</span> (logWriter
== <span style="color: blue">null</span>)</pre>
          <pre style="margin: 0px">        {</pre>
          <pre style="margin: 0px">            <span style="color: blue">throw</span><span style="color: blue">new</span><span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">"logWriter"</span>);</pre>
          <pre style="margin: 0px">        }        </pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.filter
= filter;</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.logWriter
= logWriter;</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#region</span> IExceptionFilter Members</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">    <span style="color: blue">public</span><span style="color: blue">void</span> OnException(<span style="color: #2b91af">ExceptionContext</span> filterContext)</pre>
          <pre style="margin: 0px">    {</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.logWriter.WriteError(filterContext.Exception);</pre>
          <pre style="margin: 0px">        <span style="color: blue">this</span>.filter.OnException(filterContext);</pre>
          <pre style="margin: 0px">    }</pre>
          <pre style="margin: 0px"> </pre>
          <pre style="margin: 0px">
            <span style="color: blue">   
#endregion</span>
          </pre>
          <pre style="margin: 0px">}</pre>
        </div>
        <p>
The LoggingExceptionFilter shown above is unabridged production code. This is all
it takes to bridge the gap between IExceptionFilter and some ILogWriter interface
(replace with the logging framework of your choice). Notice how it simply logs the
error and then passes on exception handling to the decorated IExceptionFilter.
</p>
        <p>
Currently we use HandleErrorAttribute as the decorated filter so that behavior stays
as expected.
</p>
        <!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 c.ActionInvoker = \par ??    \cf3 new\cf0  \cf4 ErrorHandlingControllerActionInvoker\cf0 (\par ??        \cf3 new\cf0  \cf4 LoggingExceptionFilter\cf0 (\par ??            \cf3 new\cf0  \cf4 HandleErrorAttribute\cf0 (), logWriter));}
-->
        <div style="font-family: courier new; background: white; color: black; font-size: 10pt">
          <pre style="margin: 0px">c.ActionInvoker = </pre>
          <pre style="margin: 0px">    <span style="color: blue">new</span><span style="color: #2b91af">ErrorHandlingControllerActionInvoker</span>(</pre>
          <pre style="margin: 0px">        <span style="color: blue">new</span><span style="color: #2b91af">LoggingExceptionFilter</span>(</pre>
          <pre style="margin: 0px">            <span style="color: blue">new</span><span style="color: #2b91af">HandleErrorAttribute</span>(),
logWriter));</pre>
        </div>
        <p>
This is not too different from before, except that a LoggingExceptionFilter now decorates
the HandleErrorAttribute instance.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be8504e1-b78f-4246-9338-717f7d0529b5" />
      </body>
      <title>LoggingExceptionFilter</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</guid>
      <link>http://blog.ploeh.dk/2009/12/07/LoggingExceptionFilter.aspx</link>
      <pubDate>Mon, 07 Dec 2009 06:20:27 GMT</pubDate>
      <description>&lt;p&gt;
In a previous post I described &lt;a href="http://blog.ploeh.dk/2009/12/01/GlobalErrorHandlingInASPNETMVC.aspx"&gt;how
to enable global error handling in ASP.NET MVC applications&lt;/a&gt;. Although I spent
some time talking about the importance of DRY, another major motivation for me was
to enable Dependency Injection (DI) with exception handling so that I could log stack
traces before letting ASP.NET MVC handle the exception.
&lt;/p&gt;
&lt;p&gt;
With the ErrorHandlingControllerActionInvoker I described, we can inject any IExceptionFilter
implementation. As an example I used HandleErrorAttribute, but obviously that doesn't
log anything. Once again, it would be tempting to derive from HandleErrorAttribute
and override its OnException method, but staying true to the &lt;a href="http://en.wikipedia.org/wiki/Single_responsibility_principle"&gt;Single
Responsibility Principle&lt;/a&gt; as well as the &lt;a href="http://en.wikipedia.org/wiki/Open/closed_principle"&gt;Open/Closed
Principle&lt;/a&gt; I rather prefer a &lt;a href="http://en.wikipedia.org/wiki/Decorator_pattern"&gt;Decorator&lt;/a&gt;:
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red43\green145\blue175;\red163\green21\blue21;}??\fs20 \cf1 public\cf0  \cf1 class\cf0  \cf4 LoggingExceptionFilter\cf0  : \cf4 IExceptionFilter\par ??\cf0 \{\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 IExceptionFilter\cf0  filter;\par ??    \cf1 private\cf0  \cf1 readonly\cf0  \cf4 ILogWriter\cf0  logWriter;\par ??\par ??    \cf1 public\cf0  LoggingExceptionFilter(\cf4 IExceptionFilter\cf0  filter,\par ??        \cf4 ILogWriter\cf0  logWriter)\par ??    \{\par ??        \cf1 if\cf0  (filter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "filter"\cf0 );\par ??        \}\par ??        \cf1 if\cf0  (logWriter == \cf1 null\cf0 )\par ??        \{\par ??            \cf1 throw\cf0  \cf1 new\cf0  \cf4 ArgumentNullException\cf0 (\cf5 "logWriter"\cf0 );\par ??        \}        \par ??    \par ??        \cf1 this\cf0 .filter = filter;\par ??        \cf1 this\cf0 .logWriter = logWriter;\par ??    \}\par ??\par ??\cf1     #region\cf0  IExceptionFilter Members\par ??\par ??    \cf1 public\cf0  \cf1 void\cf0  OnException(\cf4 ExceptionContext\cf0  filterContext)\par ??    \{\par ??        \cf1 this\cf0 .logWriter.WriteError(filterContext.Exception);\par ??        \cf1 this\cf0 .filter.OnException(filterContext);\par ??    \}\par ??\par ??\cf1     #endregion\par ??\cf0 \}}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt; : &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;{&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;readonly&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ILogWriter&lt;/span&gt; logWriter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; LoggingExceptionFilter(&lt;span style="color: #2b91af"&gt;IExceptionFilter&lt;/span&gt; filter,&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: #2b91af"&gt;ILogWriter&lt;/span&gt; logWriter)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (filter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"filter"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;if&lt;/span&gt; (logWriter
== &lt;span style="color: blue"&gt;null&lt;/span&gt;)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;throw&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ArgumentNullException&lt;/span&gt;(&lt;span style="color: #a31515"&gt;"logWriter"&lt;/span&gt;);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter
= filter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.logWriter
= logWriter;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#region&lt;/span&gt; IExceptionFilter Members&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; OnException(&lt;span style="color: #2b91af"&gt;ExceptionContext&lt;/span&gt; filterContext)&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; {&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.logWriter.WriteError(filterContext.Exception);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;this&lt;/span&gt;.filter.OnException(filterContext);&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; }&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&lt;span style="color: blue"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;
#endregion&lt;/span&gt;&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The LoggingExceptionFilter shown above is unabridged production code. This is all
it takes to bridge the gap between IExceptionFilter and some ILogWriter interface
(replace with the logging framework of your choice). Notice how it simply logs the
error and then passes on exception handling to the decorated IExceptionFilter.
&lt;/p&gt;
&lt;p&gt;
Currently we use HandleErrorAttribute as the decorated filter so that behavior stays
as expected.
&lt;/p&gt;
&lt;!--
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue255;\red43\green145\blue175;}??\fs20 c.ActionInvoker = \par ??    \cf3 new\cf0  \cf4 ErrorHandlingControllerActionInvoker\cf0 (\par ??        \cf3 new\cf0  \cf4 LoggingExceptionFilter\cf0 (\par ??            \cf3 new\cf0  \cf4 HandleErrorAttribute\cf0 (), logWriter));}
--&gt;
&lt;div style="font-family: courier new; background: white; color: black; font-size: 10pt"&gt;&lt;pre style="margin: 0px"&gt;c.ActionInvoker = &lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;ErrorHandlingControllerActionInvoker&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;LoggingExceptionFilter&lt;/span&gt;(&lt;/pre&gt;&lt;pre style="margin: 0px"&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp; &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;HandleErrorAttribute&lt;/span&gt;(),
logWriter));&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This is not too different from before, except that a LoggingExceptionFilter now decorates
the HandleErrorAttribute instance.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=be8504e1-b78f-4246-9338-717f7d0529b5" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,be8504e1-b78f-4246-9338-717f7d0529b5.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=3bdeeded-974f-4bcd-8042-4928c1459e90</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=3bdeeded-974f-4bcd-8042-4928c1459e90</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
          <a href="http://danielfrost.dk/">Daniel Frost</a> has published a podcast where he
discusses Dependency Injection with me. It's about half an hour long and in Danish. <a href="http://danielfrost.dk/post/Frosts-Podcast-Show-7-e28093-Dependency-Injections-med-Mark-Seemann.aspx">Hear
it here</a>.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3bdeeded-974f-4bcd-8042-4928c1459e90" />
      </body>
      <title>Dependency Injection Podcast with me</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/17/DependencyInjectionPodcastWithMe.aspx</link>
      <pubDate>Tue, 17 Nov 2009 18:58:47 GMT</pubDate>
      <description>&lt;p&gt;
&lt;a href="http://danielfrost.dk/"&gt;Daniel Frost&lt;/a&gt; has published a podcast where he
discusses Dependency Injection with me. It's about half an hour long and in Danish. &lt;a href="http://danielfrost.dk/post/Frosts-Podcast-Show-7-e28093-Dependency-Injections-med-Mark-Seemann.aspx"&gt;Hear
it here&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=3bdeeded-974f-4bcd-8042-4928c1459e90" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,3bdeeded-974f-4bcd-8042-4928c1459e90.aspx</comments>
      <category>Dependency Injection</category>
      <category>Miscellaneous</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=4276a194-a567-47ab-80b3-23c2813537f3</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=4276a194-a567-47ab-80b3-23c2813537f3</wfw:commentRss>
      <slash:comments>2</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When using <a href="http://castleproject.org/container/index.html">Castle Windsor</a> in
web applications you would want to register many of your components with a lifestyle
that is associated with a single request. This is the purpose of the PerWebRequest
lifestyle.
</p>
        <p>
If you try that with ASP.NET MVC on IIS7, you are likely to receive the following
error message:
</p>
        <blockquote>
          <p>
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule 
<br />
Add '&lt;add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" /&gt;' to the &lt;httpModules&gt; section on your web.config.
</p>
        </blockquote>
        <p>
Unfortunately, following the instructions in the error message doesn't help. There's
a <a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e/1c33a54539f8abf7">discussion
about this issue</a> on the Castle Project Users forum, but the gist of it is that
if you don't need to <em>resolve</em> components during application startup, this
shouldn't be an issue, and indeed it isn't – it seems to be something else. 
</p>
        <p>
In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules
instead of configuration/system.web/httpModules. 
</p>
        <p>
Although I haven't had the opportunity to dive into the technical details to understand <em>why</em> this
works, this seems to solve the problem on both Windows Vista and Windows Server 2008.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4276a194-a567-47ab-80b3-23c2813537f3" />
      </body>
      <title>Using Castle Windsor's PerWebRequest lifestyle with ASP.NET MVC on IIS7</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</guid>
      <link>http://blog.ploeh.dk/2009/11/17/UsingCastleWindsorsPerWebRequestLifestyleWithASPNETMVCOnIIS7.aspx</link>
      <pubDate>Tue, 17 Nov 2009 12:44:37 GMT</pubDate>
      <description>&lt;p&gt;
When using &lt;a href="http://castleproject.org/container/index.html"&gt;Castle Windsor&lt;/a&gt; in
web applications you would want to register many of your components with a lifestyle
that is associated with a single request. This is the purpose of the PerWebRequest
lifestyle.
&lt;/p&gt;
&lt;p&gt;
If you try that with ASP.NET MVC on IIS7, you are likely to receive the following
error message:
&lt;/p&gt;
&lt;blockquote&gt; 
&lt;p&gt;
Looks like you forgot to register the http module Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule 
&lt;br&gt;
Add '&amp;lt;add name="PerRequestLifestyle" type="Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule,
Castle.MicroKernel" /&amp;gt;' to the &amp;lt;httpModules&amp;gt; section on your web.config.
&lt;/p&gt;
&lt;/blockquote&gt; 
&lt;p&gt;
Unfortunately, following the instructions in the error message doesn't help. There's
a &lt;a href="http://groups.google.com/group/castle-project-users/browse_thread/thread/d44d96f4b548611e/1c33a54539f8abf7"&gt;discussion
about this issue&lt;/a&gt; on the Castle Project Users forum, but the gist of it is that
if you don't need to &lt;em&gt;resolve&lt;/em&gt; components during application startup, this
shouldn't be an issue, and indeed it isn't – it seems to be something else. 
&lt;p&gt;
In my case I seem to have solved the problem by registering the HTTP module in configuration/system.webServer/modules
instead of configuration/system.web/httpModules. 
&lt;p&gt;
Although I haven't had the opportunity to dive into the technical details to understand &lt;em&gt;why&lt;/em&gt; this
works, this seems to solve the problem on both Windows Vista and Windows Server 2008.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=4276a194-a567-47ab-80b3-23c2813537f3" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,4276a194-a567-47ab-80b3-23c2813537f3.aspx</comments>
      <category>ASP.NET MVC</category>
      <category>Castle Windsor</category>
      <category>Dependency Injection</category>
    </item>
    <item>
      <trackback:ping>http://blog.ploeh.dk/Trackback.aspx?guid=6caf04d0-c866-492e-8f1e-289af8739a69</trackback:ping>
      <pingback:server>http://blog.ploeh.dk/pingback.aspx</pingback:server>
      <pingback:target>http://blog.ploeh.dk/PermaLink,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</pingback:target>
      <dc:creator>Mark Seemann</dc:creator>
      <wfw:comment>http://blog.ploeh.dk/CommentView,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</wfw:comment>
      <wfw:commentRss>http://blog.ploeh.dk/SyndicationService.asmx/GetEntryCommentsRss?guid=6caf04d0-c866-492e-8f1e-289af8739a69</wfw:commentRss>
      <slash:comments>4</slash:comments>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
For the last few months I've been writing a book for Manning tentatively titled <em>Dependency
Injection in .NET</em>. The <a href="http://www.manning.com/seemann/">page about the
book</a> is now live at the <a href="http://www.manning.com/">Manning</a> web site
where you can read more about it and, if you would like, purchase an Early Access
edition and read the chapters as they are being written.
</p>
        <p>
If you have ever wanted to learn about Dependency Injection (DI) related to .NET,
here's your chance!
</p>
        <p>
At the moment I'm about a third of the way into the book, so there's still some way
to go, but I hope to be done with it in 2010.
</p>
        <p>
If you decide to purchase an Early Access edition, I'd love to receive your feedback
in the online forum.
</p>
        <img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6caf04d0-c866-492e-8f1e-289af8739a69" />
      </body>
      <title>Writing a book</title>
      <guid isPermaLink="false">http://blog.ploeh.dk/PermaLink,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</guid>
      <link>http://blog.ploeh.dk/2009/10/05/WritingABook.aspx</link>
      <pubDate>Mon, 05 Oct 2009 18:13:50 GMT</pubDate>
      <description>&lt;p&gt;
For the last few months I've been writing a book for Manning tentatively titled &lt;em&gt;Dependency
Injection in .NET&lt;/em&gt;. The &lt;a href="http://www.manning.com/seemann/"&gt;page about the
book&lt;/a&gt; is now live at the &lt;a href="http://www.manning.com/"&gt;Manning&lt;/a&gt; web site
where you can read more about it and, if you would like, purchase an Early Access
edition and read the chapters as they are being written.
&lt;/p&gt;
&lt;p&gt;
If you have ever wanted to learn about Dependency Injection (DI) related to .NET,
here's your chance!
&lt;/p&gt;
&lt;p&gt;
At the moment I'm about a third of the way into the book, so there's still some way
to go, but I hope to be done with it in 2010.
&lt;/p&gt;
&lt;p&gt;
If you decide to purchase an Early Access edition, I'd love to receive your feedback
in the online forum.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://blog.ploeh.dk/aggbug.ashx?id=6caf04d0-c866-492e-8f1e-289af8739a69" /&gt;</description>
      <comments>http://blog.ploeh.dk/CommentView,guid,6caf04d0-c866-492e-8f1e-289af8739a69.aspx</comments>
      <category>Dependency Injection</category>
    </item>
  </channel>
</rss>