<?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; C#</title>
	<atom:link href="http://stefanoricciardi.com/category/net/c-net/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>Code Snippets for the Dispose Pattern</title>
		<link>http://stefanoricciardi.com/2011/05/25/code-snippets-for-the-dispose-pattern/</link>
		<comments>http://stefanoricciardi.com/2011/05/25/code-snippets-for-the-dispose-pattern/#comments</comments>
		<pubDate>Wed, 25 May 2011 14:08:34 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[snippet]]></category>
		<category><![CDATA[tips]]></category>
		<category><![CDATA[visual studio 2010]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1407</guid>
		<description><![CDATA[         ]]></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%2F05%2F25%2Fcode-snippets-for-the-dispose-pattern%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2011%2F05%2F25%2Fcode-snippets-for-the-dispose-pattern%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p>I thougth I&#8217;d just share a couple of Visual Studio C# code snippets to implement disposable classes, based on the well known .NET <a href="http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx">dispose pattern</a>.</p>
<p>You can download it from <a href="http://stefanoricciardi.com/blog/wp-content/uploads/2011/05/DisposePattern.zip">here</a> or simply copy and past it from the listing below. Feel free to rename the shortcut to whatever you like <img src='http://stefanoricciardi.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<pre class="brush:xml">
&lt;?xml version="1.0" encoding="utf-8" ?&gt;
&lt;CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet"&gt;
  &lt;CodeSnippet Format="1.0.0"&gt;
    &lt;Header&gt;
      &lt;Title&gt;Base class disposable implementation.&lt;/Title&gt;
      &lt;Shortcut&gt;bdisp&lt;/Shortcut&gt;
      &lt;Description&gt;
        Code snippet to create a scheleton implementation
        of the IDisposable pattern for a base class.
      &lt;/Description&gt;
      &lt;Author&gt;Stefano Ricciardi&lt;/Author&gt;
      &lt;SnippetTypes&gt;
        &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
    &lt;/Header&gt;
    &lt;Snippet&gt;
      &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;ClassName&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the class.&lt;/ToolTip&gt;
          &lt;Default&gt;ClassName&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language="csharp"&gt;
        &lt;![CDATA[
    public class $ClassName$: IDisposable
    {
        private bool _disposed = false;

        //Implement IDisposable.
        public void Dispose()
        {
          Dispose(true);
          GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
          if (!_disposed)
          {
            if (disposing)
            {
              // Free other state (managed objects).
            }
            // Free your own state (unmanaged objects).
            // Set large fields to null.
            _disposed = true;
          }
        }

        // Use C# destructor syntax for finalization code.
        ~$ClassName$()
        {
          // Simply call Dispose(false).
          Dispose(false);
        }
    }            ]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
  &lt;CodeSnippet Format="1.0.0"&gt;
    &lt;Header&gt;
      &lt;Title&gt;Base class disposable implementation.&lt;/Title&gt;
      &lt;Shortcut&gt;ddisp&lt;/Shortcut&gt;
      &lt;Description&gt;
        Code snippet to create a scheleton implementation of the
        IDisposable pattern	for a derived class.
      &lt;/Description&gt;
      &lt;Author&gt;Stefano Ricciardi&lt;/Author&gt;
      &lt;SnippetTypes&gt;
        &lt;SnippetType&gt;Expansion&lt;/SnippetType&gt;
      &lt;/SnippetTypes&gt;
    &lt;/Header&gt;
    &lt;Snippet&gt;
      &lt;Declarations&gt;
        &lt;Literal&gt;
          &lt;ID&gt;DerivedClassName&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the derived class.&lt;/ToolTip&gt;
          &lt;Default&gt;Derived&lt;/Default&gt;
        &lt;/Literal&gt;
        &lt;Literal&gt;
          &lt;ID&gt;BaseClassName&lt;/ID&gt;
          &lt;ToolTip&gt;Name of the base class.&lt;/ToolTip&gt;
          &lt;Default&gt;Base&lt;/Default&gt;
        &lt;/Literal&gt;
      &lt;/Declarations&gt;
      &lt;Code Language="csharp"&gt;
        &lt;![CDATA[
  public class $DerivedClassName$: $BaseClassName$
  {
      private bool _disposed = false;

      protected override void Dispose(bool disposing)
      {
          if (!_disposed)
          {
              if (disposing)
              {
                  // Release managed resources.
              }
              // Release unmanaged resources.
              // Set large fields to null.
              // Call Dispose on your base class.

              _disposed = true;
          }

          base.Dispose(disposing);
      }
      // The derived class does not have a Finalize method
      // or a Dispose method without parameters because it inherits
      // them from the base class.
  }
]]&gt;
      &lt;/Code&gt;
    &lt;/Snippet&gt;
  &lt;/CodeSnippet&gt;
&lt;/CodeSnippets&gt;
</pre>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2011/05/25/code-snippets-for-the-dispose-pattern/feed/</wfw:commentRss>
		<slash:comments>0</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>File Transfer with WCF: Part III</title>
		<link>http://stefanoricciardi.com/2010/09/02/file-transfer-with-wcf-part-iii/</link>
		<comments>http://stefanoricciardi.com/2010/09/02/file-transfer-with-wcf-part-iii/#comments</comments>
		<pubDate>Thu, 02 Sep 2010 12:08:55 +0000</pubDate>
		<dc:creator>stefanoricciardi</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[WCF]]></category>
		<category><![CDATA[SOA]]></category>

		<guid isPermaLink="false">http://stefanoricciardi.com/?p=1099</guid>
		<description><![CDATA[This is the third post on a small series about transferring large files with WCF using streaming : File Transfer With WCF File Transfer With WCF: Part II File Transfer With WCF: Part III I am closing this series of posts by sharing a skeleton for the client side handling of the uploaded and downloaded [...]]]></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%2F09%2F02%2Ffile-transfer-with-wcf-part-iii%2F"><br />
				<img src="http://api.tweetmeme.com/imagebutton.gif?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F02%2Ffile-transfer-with-wcf-part-iii%2F&amp;style=normal&amp;b=2" height="61" width="50" /><br />
			</a>
		</div>
<p><em>This is the third post on a small series about transferring large files with WCF using streaming</em> :</p>
<ul>
<li><a href="http://stefanoricciardi.com/2009/08/28/file-transfer-with-wcp/">File Transfer With WCF</a></li>
<li><a href="http://stefanoricciardi.com/2009/10/02/file-transfer-with-wcf-part-ii/">File Transfer With WCF: Part II</a></li>
<li><a href="http://stefanoricciardi.com/2010/09/02/file-transfer-with-wcf-part-iii/">File Transfer With WCF: Part III</a></li>
</ul>
<p>I am closing this series of posts by sharing a skeleton for the client side handling of the uploaded and downloaded files. Please note that the following are excerpt from a larger context and so will not compile in your environment <em>as is</em>: they are only intended to give a rough idea of how the files can be handled.</p>
<h3>Download</h3>
<pre class="brush:csharp">
 private void IssueDownloadRequest(string localFile, string serviceUrl, FileDownloadMessage request)
{
    this.service = this.proxy.OpenProxy(serviceUrl);

    try
    {
        using (FileDownloadReturnMessage response = this.service.DownloadFile(request))
        {
            if (response != null &#038;&#038; response.FileByteStream != null)
            {
                SaveFile(response.FileByteStream, localFile);
            }
        }

        this.proxy.CloseProxy(this.service);
    }
    catch (Exception e)
    {
        throw new FileTransferProxyException("Error while downloading the file", e);
    }
    finally
    {
        // we expect the stream returned from the server to be closed by the
        // server itself so nothing to be done with it here. Just abort
        // the proxy if needed.
        this.proxy.AbortProxyIfNeeded(this.service);
    }
}

private static void SaveFile(Stream saveFile, string localFilePath)
{
    const int bufferSize = 65536; // 64K

    using (FileStream outfile = new FileStream(localFilePath, FileMode.Create))
    {
        byte[] buffer = new byte[bufferSize];
        int bytesRead = saveFile.Read(buffer, 0, bufferSize);

        while (bytesRead > 0)
        {
            outfile.Write(buffer, 0, bytesRead);
            bytesRead = saveFile.Read(buffer, 0, bufferSize);
        }
    }
}
</pre>
<h3>Upload</h3>
<pre class="brush:csharp">
public void UploadFile(string localFileName, string serviceUrl, FileTypeEnum fileType)
{
    this.service = this.proxy.OpenProxy(serviceUrl);
    try
    {
        using (Stream fileStream = new FileStream(localFileName, FileMode.Open, FileAccess.Read))
        {
            var request = new FileUploadMessage();
            string remoteFileName = null;
            if (fileType == FileTypeEnum.Generic)
            {
                // we are using the service as a "FTP on WCF"
                // give the remote file the same name as the local one
                remoteFileName = Path.GetFileName(localFileName);
            }

            var fileMetadata = new FileMetaData(localFileName, remoteFileName, fileType);
            request.MetaData = fileMetadata;
            request.FileByteStream = fileStream;

            this.service.UploadFile(request);
            this.proxy.CloseProxy(this.service);
        }
    }
    catch (IOException)
    {
        throw new FileTransferProxyException("Unable to open the file to upload");
    }
    catch (Exception e)
    {
        throw new FileTransferProxyException(e.Message);
    }
    finally
    {
        this.proxy.AbortProxyIfNeeded(this.service);
    }
 }
</pre>
<p><a href="http://www.dotnetkicks.com/kick/?url=http://stefanoricciardi.com/2010/09/02/file-transfer-with-wcf-part-iii/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://stefanoricciardi.com/2010/09/02/file-transfer-with-wcf-part-iii/" border="0" alt="kick it on DotNetKicks.com" /></a></p>
<p><a rev="vote-for" href="http://dotnetshoutout.com/File-Transfer-with-WCF-Part-III-Stefano-Ricciardi"><img alt="Shout it" src="http://dotnetshoutout.com/image.axd?url=http%3A%2F%2Fstefanoricciardi.com%2F2010%2F09%2F02%2Ffile-transfer-with-wcf-part-iii%2F" style="border:0px"/></a></p>

]]></content:encoded>
			<wfw:commentRss>http://stefanoricciardi.com/2010/09/02/file-transfer-with-wcf-part-iii/feed/</wfw:commentRss>
		<slash:comments>29</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>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>
	</channel>
</rss>

