<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Stefano Ricciardi &#187; Design and Patterns</title>
	<atom:link href="http://stefanoricciardi.com/tag/design-and-patterns/feed/" rel="self" type="application/rss+xml" />
	<link>http://stefanoricciardi.com</link>
	<description>On Software Development and Thereabouts</description>
	<lastBuildDate>Tue, 15 Nov 2011 07:57:34 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Dependency Injection for Dummies</title>
		<link>http://stefanoricciardi.com/2011/11/08/dependency-injection-for-dummies/</link>
		<comments>http://stefanoricciardi.com/2011/11/08/dependency-injection-for-dummies/#comments</comments>
		<pubDate>Tue, 08 Nov 2011 09:10:31 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[agile]]></category>
		<category><![CDATA[IoC]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1487</guid>
		<description><![CDATA[Antonio Vidal has translated this post into Spanish: you can find it here. Dependency injection is a very simple concept: if you have an object that interacts with other objects the responsibility of finding a reference to those objects at run time is moved outside of the object itself. What does it mean for an [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F11%2F08%2Fdependency-injection-for-dummies%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F11%2F08%2Fdependency-injection-for-dummies%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em><a href="http://codecriticon.com/">Antonio Vidal</a> has translated this post into Spanish: you can find it <a href="http://codecriticon.com/dependencia-inyeccion-dummies/">here</a>.</em></p>
<p>Dependency injection is a very simple concept: if you have an object that interacts with other objects the responsibility of finding a reference to those objects at run time is moved outside of the object itself.</p>
<p>What does it mean for an object to &quot;interact&quot; with other objects? Generally it means invoking methods or reading properties from those objects. So if we have a class <code>A</code> that invokes method <code>Calculate</code> on class <code>B</code>, we can say that <code>A</code> interacts with <code>B</code>.</p>
<p>In the following example we show class <code>A</code> interacting with class <code>B</code>. We can equally say that <class>A</class> <i>depends</i> on class <code>B</code> to fulfill a responsibility. In this case, it not only invokes its method <code>Calculate</code> but it also creates a new instance of that class.</p>
<pre class="brush:csharp">class A
{
  private B _b;

  public A
  {
    _b = new B();
  }

  public int SomeMethod()
  {
    return (_b.Calculate() * 2);
  }
}</pre>
<p>In the following example, on the other side, the responsibility of getting a reference to an implementation of a class of type <code>B</code> is moved <i>outside</i> of <code>A</code>:</p>
<pre class="brush:csharp">class A
{
  private B _b;
  public A(B b)
  {
    _b = b;
  }
  public int SomeMethod()
  {
    return _(b.Calculate * 2);
  }
}</pre>
<p>In this case we say that a dependency (<code>B</code>) has been <i>injected</i> into <code>A</code>, via the constructor. Of course, you can also inject dependencies via a property (or even a regular method), like in the following example:</p>
<pre class="brush:csharp">class A
{
  private B _b;

  public B B
  {
     get { return _b; }
     set { _b = value; }
  }

  public int SomeMethod()
  {
    if (_b != null)
        return _b.RetrieveValue() * 2;}
    else
        // HANDLE THIS ERROR CASE
        return -1;
  }
}</pre>
<p>So this is all there is about dependency injection. Everything else just builds on this core concept.</p>
<p>Like for example Inversion Of Control (IoC) tools which helps you wiring together your objects at run time, injecting all dependencies as needed. So what exactly is Inversion of Control and how does it relate to Dependency Injection (DI)?</p>
<p>I like to associate IoC to the <a href="http://en.wikipedia.org/wiki/Hollywood_Principle">Hollywood Principle</a>: &quot;<em>Don&#39;t call us, we&#39;ll call you</em>&quot;. IoC is a design principle where <quote>reusable generic code controls the execution of problem-specific code</quote>: it is a characteristic of many frameworks, where the application is built extending or customizing a common skeleton; you put your own classes at specific points and the framework will call you when needed.</p>
<p>You can use an IoC container as a framework to perform Dependency Injection on your behalf: you tell the container which are the concrete implementation classes for your dependencies and the container will make sure that your constructors or setters will be called with the right objects.</p>
<p>Therefore, IoC containers are just a <i>convenience</i> to simplify how dependency injection is handled. But even if you don&#39;t use one you could still manually perform dependency injection.</p>
<p>(If you want to have a look at how an IoC container works you can jump to my <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">mini tutorial on Ninject</a>).</p>
<p>Why is the concept of dependency injection important? Because by applying it, you simplify your design (separating the responsibility of using an object from the responsibility of retrieving that object) and your code becomes much easier to test, since you can mock out the dependencies substituting them with fake (stub) objects. But that is the subject for another post.</p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/11/08/dependency-injection-for-dummies/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Ninject Mini Tutorial &#8211; Part 2</title>
		<link>http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/</link>
		<comments>http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/#comments</comments>
		<pubDate>Fri, 04 Feb 2011 13:17:43 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1337</guid>
		<description><![CDATA[Go to Part 1 &#160; Controlling the Life Cycle of your Objects In the previous post we did not concern ourselves with the lifecycle of the object returned from Ninject kernel. Ninject provides the following 4 built-in lifecycles (scopes): Transient (default) Singleton (only one instance) Thread (one instance per thread) Request (one instance per web [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F02%2F04%2Fninject-mini-tutorial-part-2%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F02%2F04%2Fninject-mini-tutorial-part-2%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em>Go to <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Part 1</a></em></p>
<p>&nbsp;</p>
<h2>Controlling the Life Cycle of your Objects</h2>
<p>In the previous post we did not concern ourselves with the lifecycle of the object returned from Ninject kernel. Ninject provides the following 4 built-in lifecycles (<em>scopes</em>):</p>
<ol>
<li>Transient (default)</li>
<li>Singleton (only one instance)</li>
<li>Thread (one instance per thread)</li>
<li>Request (one instance per web request).</li>
</ol>
<p>You can create <em>custom scopes</em> if needed.</p>
<h4>Singleton:</h4>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
        .To&lt;TaxCalculator&gt;()
        .InSingletonScope()
        .WithConstructorArgument(&quot;rate&quot;, .2M);

    var tc1 = kernel.Get&lt;ITaxCalculator&gt;();
    var tc2 = kernel.Get&lt;ITaxCalculator&gt;();

    Assert.Same(tc1, tc2);
}</pre>
<h4>Transient:</h4>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
        .To&lt;TaxCalculator&gt;()
        .InTransientScope()
        .WithConstructorArgument(&quot;rate&quot;, .2M);

        var tc1 = kernel.Get&lt;ITaxCalculator&gt;();
        var tc2 = kernel.Get&lt;ITaxCalculator&gt;();

        Assert.NotSame(tc1, tc2);
}</pre>
<h2>More Details on Injection Patterns</h2>
<p>With Ninject you can inject:</p>
<ol>
<li>Constructor parameters</li>
<li>Properties</li>
<li>Methods</li>
</ol>
<p>Before considering each one in turn, we just need to introduce the <code>[Inject]</code> attribute which may be used to tag constructors, properties and methods requiring injection. Obviously, by tagging constructors, properties or methods, your objects cease to be <a href="http://en.wikipedia.org/wiki/Plain_Old_CLR_Object">POCO</a>s.</p>
<h3>Constructor Injection</h3>
<p>We have already seen an example of constructor injection in <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Part I</a> when the kernel auto-magically injected an implementation of <code>ITaxCalculator</code> to the <code>Sale Area</code> constructor. In that case, even if we didn&#39;t tag the constructor with the <code>[Inject]</code> attribute, the kernel was able to perform the required binding. How?</p>
<p>That was actually a special case: when there is <em>only one</em> constructor available, the tagging is not needed. On the other hand, if there&#39;s more than one constructor defined, then then kernel can inject a dependency to only one constructor that needs to have the <code>[Inject]</code> attribute:</p>
<pre class="brush:fsharp">public class Sale3
{
    private readonly ITaxCalculator taxCalculator;

    public Sale3() { }

    [Inject]
    public Sale3(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }

    // other stuff
}</pre>
<h3>Properties Injection</h3>
<p>Instead of passing in the dependencies through the constructor, you can also inject them as properties. Injecting properties is pretty straightforward:</p>
<pre class="brush:csharp">public class Sale2
{
    [Inject]
    public ITaxCalculator TaxCalculator { get; set; } 

    // implicit default constructor and other stuff... 

    public decimal GetTotal()
    {
        decimal total = 0M;
        foreach (var item in lineItems)
        {
            total += TaxCalculator.CalculateTax(item.TotalPrice)
                    + item.TotalPrice;
        } 

        return total;
    }
}</pre>
<p>Usage (note that we never explicitely set the <code>TaxCalculator</code>):</p>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
                  .To&lt;TaxcCalculator&gt;()
                  .WithConstructorArgument(&quot;rate&quot;, .2M);

    var lineItem1 = new SaleLineItem(&quot;Gone with the wind&quot;, 10M, 1);
    var lineItem2 = new SaleLineItem(&quot;Casablanca&quot;, 5M, 2);

    var sale = kernel.Get&lt;Sale2&gt;(); // property injection!
    sale.AddItem(lineItem1);
    sale.AddItem(lineItem2);

    Assert.Equal(24M, sale.GetTotal());
}</pre>
<p>There&#39;s an important caveat: if you have 2 or more properties injected, the order in which each dependency is injected is not predictable. This might complicate your design, if those dependencies are coupled somehow (e.g. dependency A needs dependency B). For this kind of situations, constructor or method injection is usually preferred.</p>
<h3>Methods Injection</h3>
<p>Finally, it&rsquo;s also possible to tag methods for injection. As with constructor parameters, it&rsquo;s possible to inject more than one value at once.</p>
<pre class="brush:csharp">public class Sale4
{
    private ITaxCalculator taxCalculator;

    // other stuff

    // method injection, will be called by the kernel
    [Inject]
    public void SetTaxCalculator(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }

    public decimal GetTotal()
    {
        decimal total = 0M;
        foreach (var item in lineItems)
        {
            total += taxCalculator.CalculateTax(item.TotalPrice)
                  + item.TotalPrice;
        }

        return total;
    }
}</pre>
<p>Usage (note that we never explicitely call the <code>SetTaxCalculator</code>):</p>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);

    var lineItem1 = new SaleLineItem(&quot;Gone with the wind&quot;, 10M, 1);
    var lineItem2 = new SaleLineItem(&quot;Casablanca&quot;, 5M, 2);

    var sale = kernel.Get&lt;Sale4&gt;(); // method injection!
    sale.AddItem(lineItem1);
    sale.AddItem(lineItem2);

    Assert.Equal(24M, sale.GetTotal());
}</pre>
<p><em>Go to <a href="http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/">Part 1</a></em></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/" border="0" alt="kick it on DotNetKicks.com" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>Ninject Mini Tutorial &#8211; Part 1</title>
		<link>http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/</link>
		<comments>http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/#comments</comments>
		<pubDate>Fri, 21 Jan 2011 13:12:23 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[ninject]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1327</guid>
		<description><![CDATA[What Is Ninject There are several Inversion of Control (IoC) containers for .NET to pick from (such as Castle Windsor, Structure Map and Microsoft Unity, just to name just a few).&#160; Ninject is one of the newest entries in the arena, but it&#8217;s now sufficiently stable at version 2.0. Ninject tries to focus on &#8220;simplicity [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F21%2Fninject-mini-tutorial-part-1%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F01%2F21%2Fninject-mini-tutorial-part-1%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<h2>What Is Ninject</h2>
<p>There are several Inversion of Control (IoC) containers for .NET to pick from (such as <a href="http://stw.castleproject.org/Windsor.MainPage.ashx">Castle Windsor</a>, <a href="http://structuremap.net/structuremap/index.html">Structure Map</a> and <a href="http://msdn.microsoft.com/en-us/library/ff663144.aspx">Microsoft Unity</a>, just to name just a few).&nbsp; <a href="http://ninject.org/">Ninject</a> is one of the newest entries in the arena, but it&rsquo;s now sufficiently stable at version 2.0.</p>
<p>Ninject tries to focus on &ldquo;<em>simplicity and ease of use</em>&rdquo;, removing features that are not deemed necessary (to the point that XML configuration is not offered out-of-the box).</p>
<p>In this and following posts we&rsquo;ll explore some example of how to use Ninject. I assume that you are somehow familiar with the basic concepts of <em>Inversion of Control</em> and <em>Dependency Injection</em>; if that&rsquo;s not the case, you should consider having a look at this <a href="http://en.wikipedia.org/wiki/Inversion_of_control">wikipedia entry</a> (better yet, take some time and read Martin Fowler f<a href="http://martinfowler.com/articles/injection.html">amous post</a> on the subject).&nbsp;&nbsp;</p>
<h2>Setup</h2>
<p>Installing Ninject is quite easy: you simply download the pre-built DLLs it from <a href="http://ninject.org/download">here</a>. Since Ninject is open source, you can also get the sources from <a href="https://github.com/ninject/ninject">github</a> and build it on your own.</p>
<p>On my Windows machine, I have copied the DLLs on <em>C:\Ninject</em>.</p>
<h2>Getting your Feet Wet With Ninject</h2>
<p>Once you have Ninject DLLs somewhere on your hard-drive, in order to get started you only need to reference them (typically you only need to reference <tt>NInject.dll</tt> ). As we said, no XML configuration is required.</p>
<p>Let&rsquo;s see a few basic examples (the complete source code with unit tests I present in this series are available on <a href="https://github.com/stefanoric/NINJECTTUTORIAL">github</a>).</p>
<h3>&quot;Hello, Ninject&rdquo;</h3>
<p>Suppose we have a fairly simple service to calculate the taxes for a given amount, defined in an <code>ITaxCalculator</code> interface:</p>
<pre class="brush:csharp">decimal CalculateTax(decimal gross);</pre>
<p>and a trivial implementation <code>TaxCalculator</code> as follows:</p>
<pre class="brush:csharp">public class TaxCalculator : ITaxCalculator
{
    private readonly decimal _rate;

    public TaxCalculator(decimal rate)
    {
        _rate = rate;
    }

    public decimal CalculateTax(decimal amount)
    {
        return Math.Round(_rate * amount, 2);
    }
}</pre>
<p>Now, one or more classes might need to use an <code>ITaxCalculator</code> implementation to fulfill their responsibility (such as calculating the total price for a shopping cart). We can say that an implementation of <code>ITaxCalculator</code> is a <em>dependency</em> to them.</p>
<p>Like many IoC containers, Ninject uses a central object (which it calls the <em>kernel</em>) to provide concrete implementations of dependencies at run-time. The <code>Standard Kernel</code> is the default implementation of such an object. Let&#39;s see it in action:</p>
<pre class="brush:csharp">using (IKernel kernel = new StandardKernel())
{
    kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);

    var tc = kernel.Get&lt;ITaxCalculator&gt;();
    Assert.Equal(20M, tc.CalculateTax(100M));
}</pre>
<p>&nbsp;</p>
<p>As you can see, through a fluent interface we are instructing the kernel how to <em>bind</em> (resolve) requests for a <code>ITaxCalculator</code> to a <code>TaxCalculator</code> class (a concrete implementation), passing to its constructor a given tax rate (20% in this case).</p>
<p>The example continues showing how a client can retrieve an implementation of the service through the kernel (via the <code>Get()</code> method) and use it.</p>
<h3>Some Magic</h3>
<p>You might argue that the little example above is far from impressing. So let&rsquo;s now see Ninject performing something more clever.</p>
<p>Suppose we have a <code>Sale</code> class modeling a ongoing transaction on a ecommerce site. Such a class in our example depends on a <code>ITaxCalculator</code>to compute the final price of the shopping cart.</p>
<pre class="brush:csharp">public class Sale
{
    private readonly ITaxCalculator taxCalculator;

    public Sale(ITaxCalculator taxCalculator)
    {
        this.taxCalculator = taxCalculator;
    }

    // more stuff....

    public decimal GetTotal()
    {
	// use the tax calculator to calculate the total
    }
}</pre>
<p>We might create the sale in the obvious way, based on the preceding example:</p>
<pre class="brush:csharp">kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);
var sale = new Sale(kernel.Get&lt;ITaxCalculator&gt;());&gt;</pre>
<p>More interestingly, it&#39;s possible to let Ninject to find out how a <code>Sale</code> should be built based on the binding information it has received:</p>
<pre class="brush:csharp">kernel.Bind&lt;ITaxCalculator&gt;()
          .To&lt;TaxCalculator&gt;()
          .WithConstructorArgument(&quot;rate&quot;, .2M);
var sale = kernel.Get&lt;Sale&gt;();</pre>
<p>Ninject is smart enough to build a Sale class for us taking care of fulfilling the dependencies behind the scenes. This an example of <em>autowiring</em>, a most convenient feature of many IoC containers.</p>
<p><em>Go to <a href="http://stefanoricciardi.com/2011/02/04/ninject-mini-tutorial-part-2//">Part 2</a></em></p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/" border="0" alt="kick it on DotNetKicks.com" /></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/01/21/ninject-mini-tutorial-part-1/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>A Fluent Builder in C#</title>
		<link>http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/</link>
		<comments>http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/#comments</comments>
		<pubDate>Wed, 14 Apr 2010 20:27:40 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=884</guid>
		<description><![CDATA[When it comes to the number of arguments to pass to a function, Uncle Bob is pretty clear. Quoting from Clean Code: The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided when possible. More than three (polyadic) requires [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F04%2F14%2Fa-fluent-builder-in-c%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F04%2F14%2Fa-fluent-builder-in-c%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>When it comes to the number of arguments to pass to a function, <a href="http://www.objectmentor.com/omTeam/martin_r.html">Uncle Bob</a> is pretty clear. Quoting from <a href="http://www.amazon.co.uk/gp/product/0132350882?ie=UTF8&amp;tag=stefaricci-21&amp;linkCode=as2&amp;camp=1634&amp;creative=19450&amp;creativeASIN=0132350882">Clean Code</a><img style="margin: 0px; border-style: none !important;" src="http://www.assoc-amazon.co.uk/e/ir?t=stefaricci-21&amp;l=as2&amp;o=2&amp;a=0132350882" border="0" alt="" width="1" height="1" />:</p>
<blockquote><p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided when possible. More than three (polyadic) requires very special justification – and then shouldn’t be used anyway.</p></blockquote>
<p>Still, some objects might have more than 3 attributes or properties and you usually need some way to initialize them via the constructor. Some attribute might not be mandatory, therefore on some occasions you can get by with a few overloads adding more parameters as needed.   </p>
<p>Consider the following (contrieved) example from the world of soccer. I have picked a few attributes that encapsulate the concept of a <code>Team</code>.</p>
<pre class="brush:csharp">
namespace Soccer
{
    public enum Color
    {
        White,
        Red,
        Green,
        Blue
    }

    public class Team
    {
        string Name { get; set; }
        string NickName { get; set; }
        Color ShirtColor { get; set; }
        string HomeTown { get; set; }
        string Ground { get; set; }

        public Team(
            string name,
            string nickName,
            Color shirtColor,
            string homeTown,
            string ground)
        {
            Name = name;
            NickName = nickName;
            ShirtColor = shirtColor;
            HomeTown = homeTown;
            Ground = ground;
        }
    }
}</pre>
<p>Let&#8217;s try initializing one team:</p>
<pre class="brush:csharp">Team team1 = new Team(
    "Manchester United",
    "The Red Devils",
    Color.Red,
    "Manchester",
    "Old Trafford");
</pre>
<p>In this case we are passing 5 arguments into the constructor. Consider that most of the parameters is a string, therefore it&#8217;s quite easy to get confused and invert the order of some parameter (the first two or the last two). The compiler would not be able to help in this case.</p>
<p>What may help here is a builder object with a <a href="http://en.wikipedia.org/wiki/Fluent_interface">fluent interface</a> which can help specifying all the attributes of the team. Something like the following:</p>
<pre class="brush:csharp">TeamBuilder tb = new TeamBuilder();
Team team2 =
    tb.CreateTeam("Real Madrid")
        .WithNickName("Los Merengues")
        .WithShirtColor(Color.White)
        .FromTown("Madrid")
        .PlayingAt("Santiago Bernabeu")
        .Build();
</pre>
<p>Let&#8217;s see the code for the <code>TeamBuilder</code> class:</p>
<pre class="brush:csharp">public class TeamBuilder
{
    private string name;
    private string nickName;
    private Color shirtColor;
    private string homeTown;
    private string ground;

    public TeamBuilder CreateTeam(string name)
    {
        this.name = name;
        return this;
    }

    public TeamBuilder WithNickName(string nickName)
    {
        this.nickName = nickName;
        return this;
    }

    public TeamBuilder WithShirtColor(Color shirtColor)
    {
        this.shirtColor = shirtColor;
        return this;
    }

    public TeamBuilder FromTown(string homeTown)
    {
        this.homeTown = homeTown;
        return this;
    }

    public TeamBuilder PlayingAt(string ground)
    {
        this.ground = ground;
        return this;
    }

    public Team Build()
    {
        return new Team(name, nickName, shirtColor, homeTown, ground);
    }
}
</pre>
<p>The only catch in the solution above is that the caller needs to call <code>Build()</code> at the end of the call chain.</p>
<p>We can improve the solution using an <a href="http://msdn.microsoft.com/en-us/library/z5z9kes2%28VS.71%29.aspx">implicit user-defined type conversion operator</a>:</p>
<pre class="brush:csharp">public class TeamBuilder
{
    private string name;
    private string nickName;
    private Color shirtColor;
    private string homeTown;
    private string ground;

    public TeamBuilder CreateTeam(string name)
    {
        this.name = name;
        return this;
    }

    public TeamBuilder WithNickName(string nickName)
    {
        this.nickName = nickName;
        return this;
    }

    public TeamBuilder WithShirtColor(Color shirtColor)
    {
        this.shirtColor = shirtColor;
        return this;
    }

    public TeamBuilder FromTown(string homeTown)
    {
        this.homeTown = homeTown;
        return this;
    }

    public TeamBuilder PlayingAt(string ground)
    {
        this.ground = ground;
        return this;
    }

    // CONVERSION OPERATOR
    public static implicit operator Team(TeamBuilder tb)
    {
        return new Team(
            tb.name,
            tb.nickName,
            tb.shirtColor,
            tb.homeTown,
            tb.ground);
    }
</pre>
<p>This allows you to create new teams in a more natural way as follows:</p>
<pre class="brush:csharp">TeamBuilder tb = new TeamBuilder();

Team team3 = tb.CreateTeam("Chelsea")
    .WithNickName("The blues")
    .WithShirtColor(Color.Blue)
    .FromTown("London")
    .PlayingAt("Stamford Bridge");
</pre>
<p>The above solution, albeit quite simple, is a good starting point. To make it ready for real-world code, you should making it more robust with some error checking (what happens if I omit some call from the chain? If I pass an invalid argument? Etc&#8230;).</p>
<p>More, you might want to hide the actual implementation from the clients and extract an interface or abstract class from the concrete <code>TeamBuilder</code>. This is left to the reader as an excercise <img src='http://stefanoricciardi.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p>    <a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/"><br />
        <img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/" style="border:0px"/><br />
    </a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/04/14/a-fluent-builder-in-c/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>New Year&#039;s Resolutions for 2010</title>
		<link>http://stefanoricciardi.com/2010/01/08/new-years-resolutions-for-2010/</link>
		<comments>http://stefanoricciardi.com/2010/01/08/new-years-resolutions-for-2010/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 13:52:36 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Misc]]></category>
		<category><![CDATA[book]]></category>
		<category><![CDATA[DDD]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Subversion]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=653</guid>
		<description><![CDATA[The new year has just started and it&#8217;s time for me to share my professional life resolutions for the upcoming year. Through books, articles, blogs, podcasts, one hears about that language, or that technology, or that process which would be great to try and learn. Unfortunately, since the spare time is not infinite, one has [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F01%2F08%2Fnew-years-resolutions-for-2010%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F01%2F08%2Fnew-years-resolutions-for-2010%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>The new year has just started and it&#8217;s time for me to share my professional life resolutions for the upcoming year.</p>
<p>Through books, articles, blogs, podcasts, one hears about that language, or that technology, or that process which would be great to try and learn. Unfortunately, since the spare time is not infinite, one has to make choices and concentrate on what might give the best return on investment in the short/medium term. The following are the two or three things which I have chosen to dive in this year:<br />
<!-- more --></p>
<h3>Read the Blue Book</h3>
<p><a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/dddbook.jpg"><img class="size-full wp-image-655" style="display:inline;margin-left:5px;margin-right:0;" title="Domain Driven Design Book" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/dddbook.jpg" alt="" width="98" height="125" align="right" /></a><strong> </strong><a href="http://www.amazon.co.uk/Domain-driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1262868697&amp;sr=8-1">Domain-Driven Design</a> by Eric Evans is one of the best book that I have come across on software design in a while. Not always an easy read (some say it&#8217;is &#8220;dense&#8221;), I am going through it slower than usual: every chapter is full of sound advices and deep concepts that take a while to sink in.</p>
<p>Luckily in my current project I will have the opportunity to apply many concepts from this approach. For this reason alone, this makes to the top of my list for 2010.</p>
<h3><strong>Learn Ruby</strong></h3>
<p><a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/ruby-logo.png"><img class="alignright size-full wp-image-658" style="float:right;margin-left:0;margin-right:0;" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/ruby-logo.png" alt="Ruby Logo" width="117" height="135" /></a>2009 has been for me the year of C#. The Pragmatic Programmer suggests to both to learn a new language every year and getting familiar with one scripting language. Most experts seem to agree that learning a language with a different paradigm from the one you use everyday is a big plus. Martin Fowler (who <a href="http://martinfowler.com/bliki/EvaluatingRuby.html">favors Ruby</a>) states that:</p>
<blockquote><p>[...] programming languages do affect the way you think about programming, and learning new languages can do a lot to help you think about solving problems in different ways. (It&#8217;s important to learn languages that are quite different in order to get the benefit of this. Java and C# are too similar to count.)</p></blockquote>
<p>I am not expecting to become proficient with Ruby in the near future (after all, I will still be using C# in my every-day at work). However from what I have seen so far it really looks like a great language to learn, so I am looking forward to it.</p>
<h3>Play with Subversion</h3>
<p><a href="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/subversioncrop.png"><img style="display:inline;margin-left:0;margin-right:0;border-width:0;" title="SubversionCrop" src="http://69.175.59.226/~stefano3/blog/wp-content/uploads/2010/01/subversioncrop_thumb.png" border="0" alt="SubversionCrop" width="244" height="37" align="right" /></a> In my previous job at Motorola I was developing in a mixed Unix and Windows environment; <a href="http://www-01.ibm.com/software/awdtools/clearcase/multisite/index.html">Rational Clearcase Multisite</a> was the company-wide version control tool. Clearcase is a real heavy weight, and probably one of the few tools that can handle teams of hundreds of developers located anywhere word-wide.</p>
<p>When I landed my current job I had to switch to the much more limited (and widely <a href="http://www.codinghorror.com/blog/archives/000660.html">hated</a>) Microsoft Source Safe (hey… always better than no version control at all, right?) Luckily, rumors has it that we might soon migrate to <a href="http://subversion.tigris.org/">Subversion</a>.  Subversion is widely used in the open source community and I guess I’ll need it once I start playing with Ruby and downloading libraries etc…</p>
<h3>Other Books to Read</h3>
<p><a title="Reading Book Stack, by stevewilhelm" href="http://www.flickr.com/photos/stevewilhelm/489404053/"><img style="float:right;margin-left:5px;margin-right:0;" src="http://farm1.static.flickr.com/209/489404053_b91cd84d73_t.jpg" alt="" width="67" height="100" /></a>Beside the blue book, there are a few other books that I plan to complete reading this year. I have already started <a href="http://www.amazon.co.uk/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1262899365&amp;sr=8-1">Clean Code</a> and <a href="http://www.amazon.co.uk/Pragmatic-Thinking-Learning-Refactor-Programmers/dp/1934356050/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1262899448&amp;sr=1-1">Pragmatic Thinking and Learning</a>. Next on my list is <a href="http://www.amazon.co.uk/Working-Effectively-Legacy-Robert-Martin/dp/0131177052/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1262899498&amp;sr=1-1">Working Effectively With Legacy Code</a> and <a href="http://www.amazon.co.uk/Agile-Estimating-Planning-Robert-Martin/dp/0131479415/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1262899606&amp;sr=1-1">Agile Estimating and Planning</a>. I promised myself not to buy any more book before I clean my current queue!</p>
<h3>Stuff Left for 2011</h3>
<p>As I mentioned, there are so many other things I would love to investigate and play with, but there is only so much time available, considering that 2010 will bring in .Net4.0 and C#4.0 that will surely be a priority.</p>
<p>Therefore, the following I guess will have to wait till 2011:</p>
<ul>
<li>Learning a functional programming language (possibly Haskell or F#)</li>
<li>Getting familiar Domain Specific Languages (Martin Fowler is preparing a <a href="http://martinfowler.com/dslwip/" class="broken_link">book</a> on the topic)</li>
<li>Play with Android and/or iPhone development</li>
<li>The Next Big Thing from 2010!</li>
</ul>
<div><em>Photo of the stack of books by Steve Wilhelm (<a rel="cc:attributionURL" href="http://www.flickr.com/photos/stevewilhelm/">http://www.flickr.com/photos/stevewilhelm/</a> / <a rel="license" href="http://creativecommons.org/licenses/by-nc-sa/2.0/">CC BY-NC-SA 2.0</a>)</em></div>
<p><a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f01%2f08%2fnew-years-resolutions-for-2010%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.com%2f2010%2f01%2f08%2fnew-years-resolutions-for-2010%2f" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/New-Years-Resolutions-for-2010"><img style="border:0;" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F01%2F08%2Fnew-years-resolutions-for-2010%2F" alt="Shout it" /></a></p>
<p><!-- AddThis Button BEGIN --><br />
<a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0 none;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a><br />
<!-- AddThis Button END --></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/01/08/new-years-resolutions-for-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>A Singleton Service Locator Pattern</title>
		<link>http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/</link>
		<comments>http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/#comments</comments>
		<pubDate>Thu, 29 Oct 2009 13:40:47 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=543</guid>
		<description><![CDATA[This is the third post of a series on the Service Locator pattern. In the first post I described how to create a basic service locator for your C# application, while in the second post I introduced lazy initialization of the services. We now add another piece to our puzzle, transforming the Service Locator class [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>This is the third post of a series on the Service Locator pattern. In the <a href="http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/">first post</a> I described how to create a basic service locator for your C# application, while in the <a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">second post</a> I introduced lazy initialization of the services.</p>
<p>We now add another piece to our puzzle, transforming the Service Locator class into a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>.</p>
<h1>The Singleton Pattern</h1>
<p>The singleton is arguably the most known and controversial design pattern. Some say <a href="http://c2.com/cgi/wiki?SingletonsAreGood">singletons are good</a>, some says <a href="http://c2.com/cgi/wiki?SingletonsAreEvil">singletons are evil</a>. Eric Gamma himself (one of the <a href="http://c2.com/cgi/wiki?GangOfFour">Gang Of Four</a>) in a recent <a href="http://www.informit.com/articles/article.aspx?p=1404056">interview</a> stated that (emphasis added):</p>
<blockquote><p>When discussing which patterns to drop, we found that we still love them all. (Not really—<strong>I&#8217;m in favor of dropping Singleton. Its use is almost always a design smell.</strong>)</p></blockquote>
<p>I don&#8217;t have a strong opinion either way; I tend to use it sparingly and in the following code I will show how to apply this pattern to the service locator. There are already countless blogs discussing the pros and the cons of the singleton pattern, therefore I won&#8217;t discuss about it any further.</p>
<h1>The Singleton Service Locator</h1>
<p>The following was our initial implementation (other details of the classes have been removed for clarity). The constructor was <em>internal</em>, allowing all potential clients from within the assembly to invoke it. Clients could either pass around a reference to the created service locator, or instantiate new instances each time:</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
    // a map between contracts -&gt; concrete implementation classes
    private IDictionary&lt;Type, Type&gt; servicesType;

    // a map containing references to concrete implementation already instantiated
    // (the service locator uses lazy instantiation).
    private IDictionary&lt;Type, object&gt; instantiatedServices;

    internal ServiceLocator()
    {
        this.servicesType = new Dictionary&lt;Type, Type&gt;();
        this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

        this.BuildServiceTypesMap();
    }

    // rest of the methods
 }
</pre>
<p>To implement the singleton pattern, we make the constructor <em>private</em> and provide clients with a static method through which we can retrieve an instance of the service.</p>
<p>Note how the creation of the single instance of the ServiceLocator class is itself lazy and thread safe. There are a few variations on the theme when it comes to singleton thread safe initialization (see for example <a href="http://www.yoda.arachsys.com/csharp/singleton.html">this post</a> by Jon Skeet).</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
        // a map between contracts -&gt; concrete implementation classes
        private IDictionary&lt;Type, Type&gt; servicesType;
        private static readonly object TheLock = new Object();

        private static IServiceLocator instance;

        // a map containing references to concrete implementation already instantiated
        // (the service locator uses lazy instantiation).
        private readonly IDictionary&lt;Type, object&gt; instantiatedServices;

        private ServiceLocator()
        {
            this.servicesType = new Dictionary&lt;Type, Type&gt;();
            this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

            this.BuildServiceTypesMap();
        }

        public static IServiceLocator Instance
        {
            get
            {
                lock (TheLock) // thread safety
                {
                    if (instance == null)
                    {
                        instance = new ServiceLocator();
                    }
                }

                return instance;
            }
        }

        // rest of the methods
 }
</pre>
<p>Clients will now simply invoke the <code>GetService()</code> method through the singleton instance, without having to create a new object each time:</p>
<pre class="brush:csharp">
IServiceA service = ServiceLocator.Instance.GetService&lt;IUniverseFileServiceAdapter&gt;();
</pre>
<p><!-- Kick it BEGIN --><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F29%2Fa-singleton-service-locator-pattern" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick it END --></p>
<p>    <a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/"><br />
        <img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/"><br />
    </a></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Service Locator Pattern in C# with Lazy Initialization</title>
		<link>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/</link>
		<comments>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/#comments</comments>
		<pubDate>Tue, 13 Oct 2009 12:37:35 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=423</guid>
		<description><![CDATA[In my previous post Service Locator Pattern in C#: A Simple Example I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of lazy initialization. Defining Lazy Initialization Lazy initialization improves the performance of object creation, deferring long running initializations [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F13%2Fservice-locator-pattern-in-c-with-lazy-initialization%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F10%2F13%2Fservice-locator-pattern-in-c-with-lazy-initialization%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>In my previous post <a href="http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/">Service Locator Pattern in C#: A Simple Example</a> I introduced a fairly basic implementation of this pattern. In this post I will address one of the limitations of that implementation, introducing a form of <strong>lazy initialization</strong>.</p>
<h3>Defining Lazy Initialization</h3>
<p>Lazy initialization improves the performance of object creation, deferring long running initializations until they are really needed.</p>
<p>Suppose for example that some of the fields of an object need to be read from the database. If a client never access those fields, accessing the database to retrieve those fields has been useless and it has just made object initialization slower (often by a considerable factor).</p>
<p>Martin Fowler credits Kent Beck with the introduction of the lazy initialization pattern, and in <a href="http://www.amazon.co.uk/Enterprise-Application-Architecture-Addison-Wesley-signature/dp/0321127420">PoEAA </a>book he describes it in the following way:</p>
<blockquote><p>The basic idea is that every access to the field checks to see if it&#8217;s null. If so, it calculates the value of the field before returning the field. To make this work you have to ensure that the field is self-encapsulated, meaning that all access to the field, even from within the class, is done through a getting method.</p></blockquote>
<p>Fairly simple.</p>
<h3>The Improved Service Locator</h3>
<p>The following is the improved version of the service locator which uses lazy initialization of the services.</p>
<pre class="brush:csharp">
internal class ServiceLocator : IServiceLocator
{
    // a map between contracts -&gt; concrete implementation classes
    private IDictionary&lt;Type, Type&gt; servicesType;

    // a map containing references to concrete implementation already instantiated
    // (the service locator uses lazy instantiation).
    private IDictionary&lt;Type, object&gt; instantiatedServices;

    internal ServiceLocator()
    {
        this.servicesType = new Dictionary&lt;Type, Type&gt;();
        this.instantiatedServices = new Dictionary&lt;Type, object&gt;();

        this.BuildServiceTypesMap();
    }

    public T GetService&lt;T&gt;()
    {
        if (this.instantiatedServices.ContainsKey(typeof(T)))
        {
            return (T)this.instantiatedServices[typeof(T)];
        }
        else
        {
            // lazy initialization
            try
            {
                // use reflection to invoke the service
                ConstructorInfo constructor = servicesType[typeof(T)].GetConstructor(new Type[0]);
                Debug.Assert(constructor != null, &quot;Cannot find a suitable constructor for &quot; + typeof(T));

                T service = (T)constructor.Invoke(null);

                // add the service to the ones that we have already instantiated
                instantiatedServices.Add(typeof(T), service);

                return service;
            }
            catch (KeyNotFoundException)
            {
                throw new ApplicationException&quot;The requested service is not registered&quot;);
            }
        }
    }

    private void BuildServiceTypesMap()
    {
        servicesType.Add(typeof(IServiceA),
            typeof(ServiceA));

        servicesType.Add(typeof(IServiceB),
            typeof(ServiceB));

        servicesType.Add(typeof(IServiceC),
            typeof(ServiceC));
     }
}
</pre>
<p>We are now maintaining two separate maps:</p>
<ul>
<li><code>servicesType</code> maps an interface describing a service to a <em>type</em> T that implements that interface.</li>
<li><code>instantiatedServices</code> maps an interface to an <em>instantiated</em> object of class T.</li>
</ul>
<p>Both maps are initialized in the constructor. However only the first map is filled. Every time <code>GetService</code> is invoked, we check whether a concrete implementation of that service has already been created. If not, we create that service implementation retrieving its constructor via reflection, and we put a reference to that implementation in the <code>instantiatedServices</code> map.</p>
<p>For this to work, the service implementation needs to expose a default (parameterless) constructor.</p>
<p>If services creation time is significant, lazy initialization can save you quite some time during application start up, with very little cost in terms of increased complexity.</p>
<p><i>Next article in the series: <a href="http://stefanoricciardi.com/2009/10/29/a-singleton-service-locator-pattern/">A Singleton Service Locator</a></i></p>
<p>
<!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Service Locator Pattern in C#: A Simple Example</title>
		<link>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/</link>
		<comments>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/#comments</comments>
		<pubDate>Fri, 25 Sep 2009 12:24:31 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=366</guid>
		<description><![CDATA[A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his Inversion of Control Containers and the Dependency Injection pattern. What follows is a very simple service locator implementation [...]]]></description>
			<content:encoded><![CDATA[<div class="tweetmeme_button" style="float: right; margin-left: 10px;">
			<a href="http://api.tweetmeme.com/share?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F09%2F25%2Fservice-locator-pattern-in-csharpa-simple-example%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F09%2F25%2Fservice-locator-pattern-in-csharpa-simple-example%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>A Service Locator is a common design pattern that allows decoupling clients of services (described by a public interface) from the concrete class implementing those services. Martin Fowler has a great introduction on the topic in his <a href="http://www.martinfowler.com/articles/injection.html">Inversion of Control Containers and the Dependency Injection pattern</a>.</p>
<p>What follows is a very simple service locator implementation in C# based on generics.</p>
<p>Let&#8217;s start defining the contract of a service locator.</p>
<pre class="brush:csharp">
public interface IServiceLocator
{
    T GetService&lt;T&gt;();
}
</pre>
<p>Now let&#8217;s see a very simple implementation of this contract:</p>
<pre class="brush:csharp">
class ServiceLocator : IServiceLocator
{
	// map that contains pairs of interfaces and
	// references to concrete implementations
	private IDictionary&lt;object, object&gt; services;

	internal ServiceLocator()
	{
		services = new Dictionary&lt;object, object&gt;();

		// fill the map
		this.services.Add(typeof(IServiceA), new ServiceA());
		this.services.Add(typeof(IServiceB), new ServiceB());
		this.services.Add(typeof(IServiceC), new ServiceC());
	}

	public T GetService&lt;T&gt;()
	{
		try
		{
			return (T)services[typeof(T)];
		}
		catch (KeyNotFoundException)
		{
			throw new ApplicationException(&quot;The requested service is not registered&quot;);
		}
	}
}
</pre>
<p>As you can see,</p>
<ul>
<li>the constructor of the class registers all the available services in a dictionary. In our example, we have 3 different services accessible through <code>IServiceA</code>, <code>IServiceB</code>, and <code>IServiceC</code>. It is assumed here that <code>ServiceA</code> implements <code>IServiceA</code> and so forth.</li>
<li>the generic GetService() method returns a reference the correct implementation fetching it from the dictionary</li>
</ul>
<p>This is how a client would invoke the service:</p>
<pre class="brush:csharp">
IServiceLocator locator = new ServiceLocator();
IServiceA myServiceA = locator.GetService&lt;IServiceA&gt;();
</pre>
<p>The clients do not know the actual classes implementing the service. They only have to interact with the service locator to get to an implementation.</p>
<h3>Improvements</h3>
<p>This is as simple as it gets. There are several improvements that a real-world implementation of a service locator should consider (what follows is only a partial list):</p>
<ul>
<li>The service locator itself might be a <a href="http://en.wikipedia.org/wiki/Singleton_pattern">singleton</a>. There usually is no need to have two instances of a service locator.</li>
<li><a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">Lazy initialization</a> of services might be considered. In the example above, the constructor creates new instances for all possible services; initialization might be deferred until some client actually requests a particular service.</li>
<li>The mapping between interfaces and implementation might be more flexible using metadata (e.g. through application configuration files)</li>
</ul>
<p><em>Next article in the series: <a href="http://stefanoricciardi.com/2009/10/13/service-locator-pattern-in-c-with-lazy-initialization/">Service Locator Pattern in C# with Lazy Initialization</a></em></p>
<p><!-- AddThis Button BEGIN --></p>
<p><a href="http://www.addthis.com/bookmark.php?v=250"><img style="border:0;" src="http://s7.addthis.com/static/btn/lg-share-en.gif" alt="Bookmark and Share" width="125" height="16" /></a></p>
<p><!-- AddThis Button END --></p>
<div id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:e6ceeafa-fe5c-4bd6-a48d-325da43e5abc" class="wlWriterEditableSmartContent" style="display:inline;float:none;margin:0;padding:0;">Technorati Tags: <a rel="tag" href="http://technorati.com/tags/Programming">Programming</a>, <a rel="tag" href="http://technorati.com/tags/C%23">C#</a>, <a rel="tag" href="http://technorati.com/tags/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/09/25/service-locator-pattern-in-csharpa-simple-example/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
	</channel>
</rss>

