<?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/category/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>The Difference Between Encapsulation and Information Hiding</title>
		<link>http://stefanoricciardi.com/2009/12/06/encapsulation-and-information-hiding/</link>
		<comments>http://stefanoricciardi.com/2009/12/06/encapsulation-and-information-hiding/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 21:01:24 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[Design and Patterns]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[OOP]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.net/?p=264</guid>
		<description><![CDATA[If you ask people familiar with Object Oriented Design which are the most important concepts of the paradigm to them, you will surely hear things like classes, inheritance, polymorphism. Some may talk about genericity; somebody may even mention encapsulation or information hiding. In fact, many designers use the words encapsulation and information hiding interchangeably. Encapsulation [...]]]></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%2F12%2F06%2Fencapsulation-and-information-hiding%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2009%2F12%2F06%2Fencapsulation-and-information-hiding%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><a title="Locks by Leo Reynolds, on Flickr" href="http://www.flickr.com/photos/lwr/863297155/"><img style="float:left;margin-right:20px;" src="http://farm2.static.flickr.com/1004/863297155_17b9031799_m.jpg" alt="Locks" width="240" height="240" /></a>If you ask people familiar with Object Oriented Design which are the most important concepts of the paradigm to them, you will surely hear things like <em>classes</em>, <em>inheritance</em>, <em>polymorphism</em>. Some may talk about <em>genericity</em>; somebody may even mention <em>encapsulation</em> or <em>information hiding</em>.</p>
<p>In fact, many designers use the words encapsulation and information hiding interchangeably.</p>
<h3>Encapsulation</h3>
<p>In his book  <a href="http://www.amazon.com/Fundamentals-Object-Oriented-Design-Meilir-Page-Jones/dp/020169946X/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1260132242&amp;sr=8-1-spell">Fundamental Of Object Oriented Design in UML</a> Meilir Page-Jones gives the following definition for encapsulation:</p>
<blockquote><p><strong>Encapsulation</strong> is the grouping of related ideas into one unit, which can thereafter be referred to by a single name.</p></blockquote>
<p><em>Single name</em> is here the key word to get an insight of what encapsulation is about: a subroutine (or <em>function</em> as we call it nowadays), for example, is a name that refers to a unit of code. Something  that instead of being repeated over and over in the source code is factored out in a single place.</p>
<p>As such the function is the simplest level of encapsulation and abstraction: a designer can refer to it by name as a single entity and even forget the details of the internals and only remember its interface.</p>
<p>Encapsulation in the object oriented world expands on this concept from the subroutine level to the object level: attributes that represents the state of an object and the methods that work on them are packaged into an object type.</p>
<h3>Information Hiding</h3>
<p>The concept of <strong>information hiding</strong> is very similar and was first introduced by Parnas in his seminal paper &#8220;<a title="http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf" rel="nofollow" href="http://www.cs.umd.edu/class/spring2003/cmsc838p/Design/criteria.pdf">On the Criteria to Be Used in Decomposing Systems Into Modules&#8221;</a> (pdf) almost 40 years ago.</p>
<p>Parnas used the term discussing about which criteria lead to good <em>modularity </em>in <em>structured programming</em>:</p>
<blockquote><p>every module in the [...] decomposition is characterized by its knowledge of a design decision which it hides from all others. Its interface or definition was chosen to reveal as little as possible about its inner workings.</p></blockquote>
<p>As you see, here also we talk about some separate entity or module which has some responsibility that we need fulfilled, and we are not interested about <em>how </em>it is fulfilled. But the emphasis here is a bit more about <em>hiding</em> the details from other modules (or objects in the OO world).</p>
<p>Information hiding gives the designer the freedom to <em>modify </em>how the responsibility is fulfilled by a module/object. This is especially valuable at points where the design (or even the requirements) are likely to change.</p>
<h3>Uncle Bob Helps Explaining the Difference</h3>
<p>Maybe one of the best example explaining the difference between encapsulation and information hiding can be found in Uncle Bob&#8217;s most recent book <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882/ref=sr_1_1?ie=UTF8&amp;s=books&amp;qid=1260132316&amp;sr=1-1">Clean Code</a> (even though the author was not talking about these 2 concepts explicitely).</p>
<p>The following type is merely encapsulated: we have created a concept representing a geometrical concept (the point in a 2D space).</p>
<pre class="brush:csharp">
public class Point
{
    public double x;
    public double y;
}
</pre>
<p>The following type, on the other hand, is an example of information hiding applied to the same concept:</p>
<pre class="brush:csharp">
public interface Point
{
    double GetX();
    double GetY();
    void SetCartesian(double x, double y);
    double GetR();
    double GetTheta();
    void SetPolar(double r, double theta);
}
</pre>
<p>In this second example, the actual implementation is completely <em>hidden</em>: the client doesn&#8217;t know whether the internal representation of the point is in rectangular or polar coordinates.</p>
<p>If you are curious and want to know more, you can refer to the following <a href="http://c2.com/cgi/wiki?EncapsulationIsNotInformationHiding">wiki</a> for more opinions on the differences (or lack thereof) between encapsulation and information hiding.</p>
<p><em>Photo by <a href="http://www.flickr.com/people/lwr/">Leo Reynolds</a></em>.<br />
<!-- Kick It --><br />
<a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fstefanoricciardi.net%2f2009%2f12%2f06%2fencapsulation-and-information-hiding%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fstefanoricciardi.net%2f2009%2f12%2f06%2fencapsulation-and-information-hiding%2f" border="0" alt="kick it on DotNetKicks.com" /></a><br />
<!-- Kick It end --><br />
<a rev="vote-for" href="http://dotnetshoutout.com/Submit?url=http://stefanoricciardi.net/2009/12/06/encapsulation-and-information-hiding/"><br />
        <img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http://stefanoricciardi.net/2009/12/06/encapsulation-and-information-hiding/"><br />
    </a><br />
<!-- AddThis Button BEGIN --></p>
<p><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></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/design">Design</a>, <a rel="tag" href="http://technorati.com/tags/ood">OOD</a></div>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2009/12/06/encapsulation-and-information-hiding/feed/</wfw:commentRss>
		<slash:comments>7</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>

