<?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>edventuro.us</title>
	<atom:link href="http://edventuro.us/feed/" rel="self" type="application/rss+xml" />
	<link>http://edventuro.us</link>
	<description>Technical blog of Edward McLeod-Jones</description>
	<lastBuildDate>Sat, 03 Apr 2010 14:03:24 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>SoC, DI, IoC, WTF? A basic introduction to Dependency Injection with Ninject</title>
		<link>http://edventuro.us/2010/04/soc-di-ioc-wtf-a-basic-introduction-to-dependency-injection-with-ninject/</link>
		<comments>http://edventuro.us/2010/04/soc-di-ioc-wtf-a-basic-introduction-to-dependency-injection-with-ninject/#comments</comments>
		<pubDate>Sat, 03 Apr 2010 13:55:06 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Code]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[IoC]]></category>
		<category><![CDATA[Ninject]]></category>
		<category><![CDATA[SoC]]></category>

		<guid isPermaLink="false">http://edventuro.us/2010/04/soc-di-ioc-wtf-a-basic-introduction-to-dependency-injection-with-ninject/</guid>
		<description><![CDATA[The latest TLA (Three Letter Acronyms) du jour seem to be SoC, DI, and IoC.&#160; What do these stand for and why should you care about them?
Consider the following (very) simple console application:


Code Snippet


using System;
&#160;
namespace TightlyBoundTestApp
{
    public class Program
    {
        static void Main(string[] args)
        {
            // Load up a customer
            Customer c = new Customer();
&#160;
            // Logging should have written a message
            c.Log();
&#160;
            Console.ReadKey();
        }
    }
&#160;
    public [...]]]></description>
			<content:encoded><![CDATA[<p>The latest TLA (Three Letter Acronyms) du jour seem to be SoC, DI, and IoC.&#160; What do these stand for and why should you care about them?</p>
<p>Consider the following (very) simple console application:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:11117113-e0cb-4026-b2d2-566f02e5df0e" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">using</span> System;</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">namespace</span> TightlyBoundTestApp</li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">Program</span></li>
<li style="background: #f3f3f3">    {</li>
<li>        <span style="color:#0000ff">static</span> <span style="color:#0000ff">void</span> Main(<span style="color:#0000ff">string</span>[] args)</li>
<li style="background: #f3f3f3">        {</li>
<li>            <span style="color:#008000">// Load up a customer</span></li>
<li style="background: #f3f3f3">            <span style="color:#2b91af">Customer</span> c = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Customer</span>();</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">            <span style="color:#008000">// Logging should have written a message</span></li>
<li>            c.Log();</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>            <span style="color:#2b91af">Console</span>.ReadKey();</li>
<li style="background: #f3f3f3">        }</li>
<li>    }</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">Customer</span></li>
<li style="background: #f3f3f3">    {</li>
<li>        <span style="color:#0000ff">private</span> <span style="color:#2b91af">Logger</span> logger;</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>        <span style="color:#0000ff">public</span> Customer()</li>
<li style="background: #f3f3f3">        {</li>
<li>            logger = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Logger</span>();</li>
<li style="background: #f3f3f3">        }</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">        <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> Log()</li>
<li>        {</li>
<li style="background: #f3f3f3">            logger.LogMessage(<span style="color:#a31515">&quot;This should be logged&quot;</span>);</li>
<li>        }</li>
<li style="background: #f3f3f3">    }</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">    <span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">Logger</span></li>
<li>    {</li>
<li style="background: #f3f3f3">        <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> LogMessage(<span style="color:#0000ff">string</span> message)</li>
<li>        {</li>
<li style="background: #f3f3f3">            <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;Log: &quot;</span> + message);</li>
<li>        }</li>
<li style="background: #f3f3f3">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>In this sample application, we have a Customer class which (for example purposes) only has a single method: <strong>Log</strong>, which allows it to log a message. We might use this to keep track of the transactions done by a customer so we have an audit trail for example. The logging happens by calling the <strong>LogMessage</strong> method on an instance of the Logger class which the Customer class created in its constructor.</p>
<p>In our entry point to the program, we create a new instance of our Customer class, and tell it to log a message.&#160; If we run this, a log message will be printed to the console, then the program will exit once we press a key.</p>
<p>So, it all works okay, but there a few problems which may cause issues for us down the track.&#160; We have made our Customer class depend on our Logger class.&#160; What happens when we want to create unit tests for our Customer class?&#160; We would also have to consider our Logger class as they are tightly coupled.</p>
<p> <span id="more-79"></span>This violates the first of our TLAs: <a href="http://en.wikipedia.org/wiki/Separation_of_concerns">Separation of Concerns (SoC)</a>. &quot;<em>Separation of Concerns is the process of separating a computer program into distinct features that overlap in functionality as little as possible. A concern is any piece of interest or focus in a program.</em>” – Wikipedia
<p>How do we go about achieving this separation then? Instead of having our Customer class depend on a concrete implementation of a Logger class, we could change it to interact with an interface instead. The principle behind this is known as <a href="http://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion</a> – &quot;<em>High-level modules should not depend on low-level modules. Both should depend on abstractions.</em>&quot; – Wikipedia.</p>
<p>By changing the Customer class to interact with an ILogger interface, we could provide one implementation in our Application, and a completely different one in our tests.&#160; This design technique is known as <a href="http://en.wikipedia.org/wiki/Design_by_contract">Programming to Contract</a>.</p>
<p>So, let’s start refactoring our sample program by creating an interface for the Logger:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c7d1c26a-7007-44d9-96ba-dbb678e1aa5c" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">interface</span> <span style="color:#2b91af">ILogger</span></li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">void</span> LogMessage(<span style="color:#0000ff">string</span> message);</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p>And then we can implement that interface in our Logger class:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:c7201a60-c09e-4e51-be06-64bf9c731e58" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">Logger</span> : <span style="color:#2b91af">ILogger</span></li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> LogMessage(<span style="color:#0000ff">string</span> message)</li>
<li style="background: #f3f3f3">    {</li>
<li>        <span style="color:#2b91af">Console</span>.WriteLine(<span style="color:#a31515">&quot;Log: &quot;</span> + message);</li>
<li style="background: #f3f3f3">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>And in our test project we could implement it differently, maybe keep a reference to the last message logged so we can check it in our tests for example:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:bc719100-0031-4b69-a465-949ee473fec2" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">TestLogger</span> : <span style="color:#2b91af">ILogger</span></li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">string</span> LastMessage { <span style="color:#0000ff">get</span>; <span style="color:#0000ff">set</span>; }</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> LogMessage(<span style="color:#0000ff">string</span> message)</li>
<li style="background: #f3f3f3">    {</li>
<li>        LastMessage = message;</li>
<li style="background: #f3f3f3">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>Great, so we are now programming to contract and have an interface for our logger.&#160; But how does our Customer class know which concrete implementation of the ILogger to use?&#160; If we keep the following code:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f17c0e52-8519-422f-88da-bed22da6dc23" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> Customer()</li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">this</span>.logger = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Logger</span>();</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p>We’re no better off that where we were originally, as the Customer class is still using a concrete implementation of the Logger class.&#160; What we need to do instead is to tell which implementation of the ILogger to use.&#160; There’s a few different ways to do this.&#160; The simplest way to do this is to provide the implementation in the constructor, by changing our Customer class to the following:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:1724e330-fac1-4f3f-92a9-f80108ec1b98" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">Customer</span></li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">private</span> <span style="color:#2b91af">ILogger</span> logger;</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>    <span style="color:#0000ff">public</span> Customer(<span style="color:#2b91af">ILogger</span> logger)</li>
<li style="background: #f3f3f3">    {</li>
<li>        <span style="color:#0000ff">this</span>.logger = logger;</li>
<li style="background: #f3f3f3">    }</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">    <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> Log()</li>
<li>    {</li>
<li style="background: #f3f3f3">        logger.LogMessage(<span style="color:#a31515">&quot;This should be logged&quot;</span>);</li>
<li>    }</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p>Now when we instanciate our Customer in the main program, we pass in the implementation of the ILogger we wish to use at that point, like so:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:d5a63b37-4edc-4925-a2e5-4ce2e51f1e3f" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#008000">// Create a new customer</span></li>
<li style="background: #f3f3f3"><span style="color:#2b91af">Customer</span> c = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Customer</span>(<span style="color:#0000ff">new</span> <span style="color:#2b91af">Logger</span>());</li>
</ol></div>
</p></div>
</p></div>
<p>And in our tests, we could simply pass in an alternative implementation:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f5a996b5-037c-42dd-a075-0d08172329e2" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#008000">// Create a new customer with a test logger</span></li>
<li style="background: #f3f3f3"><span style="color:#2b91af">Customer</span> c = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Customer</span>(<span style="color:#0000ff">new</span> <span style="color:#2b91af">TestLogger</span>());</li>
</ol></div>
</p></div>
</p></div>
<p>This is the simplest form of the next of our TLAs: <a href="http://en.wikipedia.org/wiki/Dependency_Injection">Dependency Injection (DI)</a> &#8211; &quot;<em>a technique for supplying an </em><em>external dependency</em><em> (i.e. a reference) to a </em><em>software component</em><em> &#8211; that is, indicating to a part of a program which other parts it can use</em>&quot; – Wikipedia.</p>
<p>You could also use a Factory / Service Locator pattern, but we’re going to skip past that and jump straight into the last of our TLAs: <a href="http://en.wikipedia.org/wiki/Inversion_of_control">Inversion of Control (IoC)</a>, specifically IoC Containers.&#160; Containers provide a centralised place to manage dependencies.&#160; Think of a container as a dictionary which maps interfaces to implemented types. In other words, it resolves dependencies.</p>
<p>While you can code a fairly simple DependencyResolver class using Generics (see <a href="http://msdn.microsoft.com/en-us/magazine/cc337885.aspx">James Kovacs’ article</a> for one such example), there are numerous fully fledged implementations in the .Net world. Some popular options are: <a href="http://structuremap.github.com/structuremap/index.html">StructureMap</a>, <a href="http://www.castleproject.org/container/">Castle Windsor</a>, <a href="http://unity.codeplex.com/Wikipage">Microsoft’s Unity</a>, and <a href="http://ninject.org/">Ninject</a>.&#160; There are many more out there, some of which are listed on <a href="http://www.hanselman.com/blog/ListOfNETDependencyInjectionContainersIOC.aspx">Scott Hanselman’s blog</a>.</p>
<p>The rest of this post will focus on Ninject, as I feel it is the simplest to illustrate the concepts of DI without getting too bogged down.&#160; A subsequent post will revist the example using Unity instead to contrast the differences.&#160; The important thing is to remember the concepts behind these different tools are the same, so don’t get too hung up on which is ‘best’.</p>
<h2>Ninject</h2>
<p>You can <a href="http://ninject.org/">download Ninject from here</a>.</p>
<p>There are two main methods you’ll use with Ninject, <strong>Bind</strong> and <strong>Get</strong>.</p>
<p>‘Bind’ is used to map the interfaces to the implemented types, i.e. if I ask for an &lt;IBurger&gt;, give me a &lt;BigMac&gt;.&#160; The binding is usually set up in a module which extends the NinjectModule class.&#160; Binding uses generics to provide a fluent interface: Bind&lt;<em>YourInterface</em>&gt;().To&lt;<em>YourConcreteImplementation</em>&gt;();&#160; In our example program it looks like this:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ef93b6ae-f93b-479e-8255-15ec98df8e4b" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">StandardModule</span> : <span style="color:#2b91af">NinjectModule</span></li>
<li style="background: #f3f3f3">{</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">override</span> <span style="color:#0000ff">void</span> Load()</li>
<li style="background: #f3f3f3">    {</li>
<li>        Bind&lt;<span style="color:#2b91af">ILogger</span>&gt;().To&lt;<span style="color:#2b91af">Logger</span>&gt;();</li>
<li style="background: #f3f3f3">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>‘Get’ is used to actually retrieve your concrete implementations with all their dependencies ‘injected’ into them.&#160; Get is a method on the <strong>Kernel.</strong> The ‘Kernel’ is your container, and is usually an instance of the StandardKernel which is instanciated with the Module that you setup your bindings in as above.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:a756eb6d-fbf7-47b4-9c7f-ed272e3354d6" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li><span style="color:#2b91af">IKernel</span> kernel = <span style="color:#0000ff">new</span> <span style="color:#2b91af">StandardKernel</span>( <span style="color:#0000ff">new</span> <span style="color:#2b91af">StandardModule</span>() );</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#008000">// Get a new customer from our container</span></li>
<li style="background: #f3f3f3"><span style="color:#2b91af">Customer</span> c = kernel.Get&lt;<span style="color:#2b91af">Customer</span>&gt;();</li>
</ol></div>
</p></div>
</p></div>
<p>So, we set up our Kernel with a reference to our module which is binding any request for an ILogger to our Logger class.&#160; We then ‘Get’ our Customer class from the Kernel.&#160; But hang on, our Customer class isn’t implementing an interface, why do we need to get it using the Kernel?&#160; Couldn’t we just instanciate it as usual?</p>
<p>This threw me a little when I first started using Ninject until I realised that <strong>unless you get an object via the Kernel</strong>, any dependencies that object has will <strong>NOT</strong> be injected.</p>
<p>So, that’s why we use kernel.Get to retrieve our Customer.&#160; By using the kernel, it ensures that the dependency the Customer has on ILogger is injected using the binding we setup in our StandardModule.</p>
<p>Instead of using the constructor to do the injection, Ninject also allows us to use the [Inject] attribute to mark up Properties, Methods, and Fields to be injected. See: <a href="http://ninject.codeplex.com/wikipage?title=Injection%20Patterns&amp;referringTitle=Dependency%20Injection%20With%20Ninject ">http://ninject.codeplex.com/wikipage?title=Injection%20Patterns&amp;referringTitle=Dependency%20Injection%20With%20Ninject</a> for more details.</p>
<p>So, we could change our Customer class to the following:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:a07e40b7-eca3-4b6e-82c7-3275ec39dfe2" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">AlternativeCustomer</span></li>
<li style="background: #f3f3f3">{</li>
<li>    [<span style="color:#2b91af">Inject</span>]</li>
<li style="background: #f3f3f3">    <span style="color:#0000ff">public</span> <span style="color:#2b91af">ILogger</span> CustomerLogger {<span style="color:#0000ff">get</span>; <span style="color:#0000ff">set</span>;} <span style="color:#008000">// Injected automagically when required by Ninject, providing the class is instantiated via Kernal.Get</span></li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">    <span style="color:#0000ff">public</span> AlternativeCustomer()</li>
<li>    {</li>
<li style="background: #f3f3f3">        <span style="color:#008000">// No longer need to instanciate a logger in the constructor as it is injected when required.</span></li>
<li>    }</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>    <span style="color:#0000ff">public</span> <span style="color:#0000ff">void</span> Log()</li>
<li style="background: #f3f3f3">    {</li>
<li>        CustomerLogger.LogMessage(<span style="color:#a31515">&quot;This should also be logged&quot;</span>);</li>
<li style="background: #f3f3f3">    }</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>By marking the CustomerLogger property with the [Inject] attribute, whenever it is required (in the Log method for instance), Ninject will resolve the dependency, in this case mapping our ILogger to our Logger class as defined in the StandardModule.</p>
<p>In our tests then, we could create a different set of mappings by binding our ILogger to a different implementation, like our TestLogger.&#160; Dependency Injection and Mocking go together very well, and there is an extension class for Ninject called Ninject.Moq which allows you to bind directly to a mock, e.g:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:0d438a54-ff29-4e51-9a08-3c21e5edbbc4" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #000080; color: #fff; font-family: Verdana, Tahoma, Arial, sans-serif; font-weight: bold; padding: 2px 5px">Code Snippet</div>
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px;">
<li>Bind&lt;<span style="color:#2b91af">ILogger</span>&gt;().ToMock&lt;<span style="color:#2b91af">ILogger</span>&gt;();</li>
</ol></div>
</p></div>
</p></div>
<p>Hopefully that has helped you to see the power of Dependency Injection. Take a look at the attached solution to see the original tightly coupled application, the decoupled application using constructor injection, and then the same application using Ninject, along with a simple unit test using Ninject.</p>
<h2>Sample Solution:</h2>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:03bf3d96-e6fe-4b5c-9b4f-04ff921fa1dd" class="wlWriterEditableSmartContent">
<p> <a href="http://edventuro.us/wp-content/uploads/SOCIOCDIWTFAnintroductiontoDependencyInj_A1C9/NinjectTestApp.zip" target="_blank">NinjectTestApp.zip</a></p>
</div>
<h2>References:</h2>
<p>Tame Your Software Dependencies for More Flexible Apps    <br /><a href="http://msdn.microsoft.com/en-us/magazine/cc337885.aspx">http://msdn.microsoft.com/en-us/magazine/cc337885.aspx</a></p>
<p>First Steps into Dependency Injection with Ninject    <br /><a href="http://adventuresdotnet.blogspot.com/2009/08/first-steps-into-dependency-injection.html">http://adventuresdotnet.blogspot.com/2009/08/first-steps-into-dependency-injection.html</a></p>
<p>Ninject website    <br /><a href="http://ninject.org">http://ninject.org</a></p>
<p>Good video tutorial on Ninject:    <br /><a href="http://tekpub.com/view/concepts/0">http://tekpub.com/view/concepts/0</a></p>
      <div  class="img " style="width:0px;">
        <a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fedventuro.us%2f2010%2f04%2fsoc-di-ioc-wtf-a-basic-introduction-to-dependency-injection-with-ninject%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fedventuro.us%2f2010%2f04%2fsoc-di-ioc-wtf-a-basic-introduction-to-dependency-injection-with-ninject%2f" alt="kick it on DotNetKicks.com"   title="Click to enlarge" /></a>
        
      </div>
]]></content:encoded>
			<wfw:commentRss>http://edventuro.us/2010/04/soc-di-ioc-wtf-a-basic-introduction-to-dependency-injection-with-ninject/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Porting a WPF App with the Model-View-ViewModel Design Pattern to Silverlight 4</title>
		<link>http://edventuro.us/2010/03/porting-a-wpf-app-with-the-model-view-viewmodel-design-pattern-to-silverlight-4/</link>
		<comments>http://edventuro.us/2010/03/porting-a-wpf-app-with-the-model-view-viewmodel-design-pattern-to-silverlight-4/#comments</comments>
		<pubDate>Tue, 23 Mar 2010 18:07:27 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[MVVM]]></category>
		<category><![CDATA[Sample]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://edventuro.us/?p=25</guid>
		<description><![CDATA[Tim Heuer wrote glowingly about Josh Smith’s new book &#8216;Advanced MVVM&#8216; on his blog recently (http://timheuer.com/blog/archive/2010/03/04/advanced-mvvm-book-for-silverlight-wpf.aspx), so I decided to check it out.
I was reading through the comments, and saw that Josh recommended checking out an article on MSDN he’d written in Feb 2009 entitled: &#34;WPF Apps With The Model-View-ViewModel Design Pattern&#34; and get a [...]]]></description>
			<content:encoded><![CDATA[<p>Tim Heuer wrote glowingly about Josh Smith’s new book &#8216;<a href="http://joshsmithonwpf.wordpress.com/advanced-mvvm/">Advanced MVVM</a>&#8216; on his blog recently (<a href="http://timheuer.com/blog/archive/2010/03/04/advanced-mvvm-book-for-silverlight-wpf.aspx">http://timheuer.com/blog/archive/2010/03/04/advanced-mvvm-book-for-silverlight-wpf.aspx</a>), so I decided to check it out.</p>
<p>I was reading through the comments, and saw that <a href="http://joshsmithonwpf.wordpress.com/advanced-mvvm/#comment-12773">Josh recommended checking out</a> an article on MSDN he’d written in Feb 2009 entitled: &quot;<a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">WPF Apps With The Model-View-ViewModel Design Pattern</a>&quot; and get a firm grounding in that before moving on to his new book. This seemed like a good idea, so I decided I’d try migrating the WPF example app in the article over to Silverlight 4 as a way of trying out some of the new features like support for Commands, IDataErrorInfo support, etc.</p>
<p>In line with the Pareto principle, most of the migration went very smoothly and swiftly and then there were a few snags which ended up taking the bulk of the time to resolve. I’ve outlined these issues and their resolutions below in the hope that it helps someone doing something similar in future. The full completed Silverlight 4 solution is also included at the bottom of the post.</p>
<p>&#160;      <div  class="img " style="width:804px;">
                <a
          href="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_6.png"
          title="Silverlight version vs WPF version"
          
        ><img src="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_6.png" alt="Silverlight version vs WPF version" width="804" height="545" title="Click to enlarge" /></a>
        <div style="width:100%;">Silverlight version vs WPF version</div>
      </div>
<p> <span id="more-25"></span><br />
<h2>Issue One: No CollectionViewSource.GetDefaultView in Silverlight</h2>
<p>Josh uses the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.getdefaultview.aspx">CollectionViewSource.GetDefaultView</a> method in the <strong>SetActiveWorkspace</strong> method to retrieve the default view of the Workspaces ObservableCollection, and then move the current item in that view to the workspace which has been passed in, using <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcollection.movecurrentto.aspx">MoveCurrentTo</a>. This is used when one of the Hyperlinks in the left hand pane is clicked, which results in a new tab being added to the workspaces tab control. MoveCurrentTo is used to set this latest item as the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemcollection.currentitem.aspx">CurrentItem</a>, which results in that tab being selected in the tab control. </p>
<p>Unfortunately Silverlight 4 doesn&#8217;t implement the GetDefaultView method on CollectionViewSource, so we have to retrieve a view from CollectionViewSource in an alternative way. I did this by changing the <strong>SetActiveWorkspace</strong> method to take an additional parameter in the form of an instance of a CollectionViewSource. The view is then retrieved using the <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.view.aspx">View</a> property of this instance, and the rest of the code works as expected.</p>
<p>To allow for an instance of a CollectionViewSource to be passed in, we define a public property called <strong>WorkspacesViewSource</strong>, and then initialise it in the constructor of the <strong>ViewModel</strong>, and set the instance&#8217;s <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.source.aspx">Source</a> property to be the Workspaces ObservableCollection.</p>
<p>This necessitates further changes though, as we now need to bind our Workspaces tab control <strong>ItemsSource </strong>property directly to the View property of our public CollectionViewSource: WorkspacesViewSource. We can do this in the Xaml of the TabControl using the syntax: <strong>ItemsSource=&quot;{Binding WorkspacesViewSource.View}&quot;</strong>. We now also need to raise the property changed event for WorkspacesViewSource when a workspace is added or removed, so we call our <strong>base.OnPropertyChanged</strong> method in the <strong>OnWorkspacesChanged</strong> event.</p>
<p>While this worked, it was not enough to get the Workspace tabs displaying in the tab control, due to the next problem&#8230;</p>
<h2>&#160;</h2>
<h2>Issue Two: Unable to cast object of type &#8216;MVVMSilverlightDemoApp.ViewModel.AllCustomersViewModel&#8217; to type &#8216;System.Windows.Controls.TabItem&#8217;.</h2>
<p>When a new workspace is added to the collection and the ItemsSource for the Workspaces tab control is refreshed, an <strong>ArgumentException</strong> was being thrown: <em>Unable to cast object of type &#8216;MVVMSilverlightDemoApp.ViewModel.AllCustomersViewModel&#8217; to type &#8216;System.Windows.Controls.TabItem&#8217;</em>.</p>
<p>This is being throw by the <strong>OnItemsChanged</strong> event in the TabControl class. Luckily, we can look at the source code of this class as it is in the <a href="http://www.codeplex.com/Silverlight">Silverlight Toolkit</a>. In the <strong>OnItemsChanged</strong> event, we see that the TabControl casts each item in its ItemSource as a <strong>TabItem</strong>, and then if it fails the cast, it throws the ArgumentException.</p>
<p>There were a couple of options to solving this. We could subclass the TabControl and override the OnItemsChanged event to deal with our workspace items better. I started doing this, but it started rapidly escalating as there were a few Private and Internal methods and variables that the event utilised, so it began to look like I&#8217;d need to duplicate and modify the entire TabControl class, along with its dependant classes. Entirely possible, given that the source is all open, but I thought this was starting to diverge from the point of the exercise.</p>
<p>A quick search for the issue came up with <a href="http://forums.silverlight.net/forums/p/18256/275257.aspx">a post on the Silverlight forums</a> where it was mentioned that &quot;<em>TabControl doesn&#8217;t override PrepareContainerForItemOverride, so it won&#8217;t automatically wrap your data source in TabItems</em>&quot;. The post suggested that the solution was to use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx">value converter</a> on the ItemSource to turn each item into a TabItem.</p>
<p>I thought I&#8217;d try overriding the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.itemscontrol.preparecontainerforitemoverride.aspx">PrepareContainerForItemOverride</a> method in my subclassed TabControl first, however this didn&#8217;t change the ArgumentException in the OnItemsChanged event, so I added a converter: <strong>WorkspacesTabConvertor</strong>.</p>
<p>This worked, in that the TabControl now displayed a tab for each item, and it was rendered correctly. However, each time the ItemsSource was updated (by adding or removing a workspace) all the tabs were recreated, which meant any selections in the <strong>AllCustomersView</strong> or data entered in a <strong>CustomersView</strong> were lost.</p>
<p>I settled on a workaround where I created a custom collection of TabItems based on ObservableCollection called <strong>WorkspaceTabItemCollection</strong>, and gave it <strong>AddItem</strong> and <strong>RemoveItem</strong> methods which took a workspace and turned it into a <strong>TabItem</strong> and then added or removed it from the collection. Then this collection was bound to the workspaces tab control&#8217;s ItemsSource. As it was a collection of TabItems, it is displayed correctly by the TabControl.</p>
<p>As a quick and dirty way of getting WorkspaceTabItemCollection working, I was creating the TabItem contents by instantiating a new AllCustomersView or CustomerView as a <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.usercontrol.aspx">UserControl</a>, and passing in the workspace as the <a href="http://msdn.microsoft.com/en-us/library/system.windows.frameworkelement.datacontext(v=VS.90).aspx">DataContext</a>. However, this required the WorkspaceTabItemCollection to know about the various views, so I refactored it to get the appropriate data templates from the <strong>MainPageResources.xaml</strong> file and apply them instead. There&#8217;s a bit of a hack still in place to set the new TabItem as <strong>IsSelected=true</strong>, to make it become selected in the TabControl, as the Silverlight TabControl doesn&#8217;t support the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.primitives.selector.issynchronizedwithcurrentitem.aspx">IsSynchronizedWithCurrentItem</a> property, rendering the first issue with SetActiveWorkspace mostly irrelevant.&#160; Oh well.</p>
<p>Workspaces are added to or removed from the WorkspaceTabItemCollection collection by hooking into the <strong>OnWorkspacesChanged</strong> event.</p>
<p>This worked well and things were starting to take shape. The next step was to get the selections in the AllCustomersView DataGrid to be totalled and display in the &#8216;Total selected sales&#8217; area.</p>
      <div  class="img " style="width:638px;">
                <a
          href="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image.png"
          title="Tabs working"
          
        ><img src="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image.png" alt="Tabs working" width="638" height="162" title="Click to enlarge" /></a>
        <div style="width:100%;">Tabs working</div>
      </div>
<p>&#160;</p>
<h2>Issue Three: Can&#8217;t bind to DataGridRow IsSelected using a Setter Property in Silverlight</h2>
<p>In the WPF version, Josh uses a <strong>Setter</strong> on the <strong>IsSelected</strong> property in the DataGridRow style to TwoWay bind to the DataGridRow&#8217;s underlying item&#8217;s IsSelected property. Then in the <strong>AllCustomersViewModel</strong>, this is detected in the <strong>OnCustomerViewModelPropertyChanged</strong> event, and the <strong>TotalSelectedSales</strong> property is in turn updated. This returns the sum of all <strong>TotalSales</strong> of each customer who&#8217;s <strong>IsSelected</strong> flag is set as true, and is the property that the &#8216;<em>Total selected sales</em>&#8216; area is bound to in the view.</p>
<p>Unfortunately, we can&#8217;t bind to the IsSelected property of a DataGridRow in Silverlight as it&#8217;s not publicly accessible. So we need another way to figure out what gets selected in the DataGrid and when.</p>
<p>After a bit of digging I found a great post by Alexey Zakharov which <a href="http://weblogs.asp.net/alexeyzakharov/archive/2009/06/06/silverlight-tips-amp-tricks-make-silverlight-datagrid-be-more-mvvm-friendly.aspx">suggests using the CommandBehaviourBase class from Prism, and then add an attached property for the SelectionChanged event on the DataGrid</a>.</p>
<p>We can then bind to a <strong>SelectedItemsChangedCommand</strong> in our ViewModel, which calls a <strong>SetCustomersAsSelected</strong> method and passes it a reference to the DataGrid (via the CommandParameter). Once we have the reference to the DataGrid, we can access the <a href="http://msdn.microsoft.com/en-us/library/system.windows.controls.datagrid.selecteditems(VS.95).aspx">SelectedItems</a> property of the DataGrid, and update the IsSelected property on our customers which will update TotalSelectedSales as detailed above.</p>
<p>This worked nicely, although I&#8217;m not entirely happy about the ViewModel needing to about a type of UI control (DataGrid). At least it avoids being tied directly to the View though.</p>
<p>With the AllCustomersView working nicely, we move on to the CustomerView form.</p>
      <div  class="img " style="width:463px;">
                <a
          href="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_3.png"
          title="Selection working"
          
        ><img src="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_3.png" alt="Selection working" width="463" height="439" title="Click to enlarge" /></a>
        <div style="width:100%;">Selection working</div>
      </div>
<p>&#160;</p>
<h2>Issue Four: Silverlight data validation needs to match the WPF sample</h2>
<p>The <strong>CustomerViewModel</strong> translated across to Silverlight with only one slight issue: Josh uses <a href="http://msdn.microsoft.com/en-us/library/system.windows.input.commandmanager.invalidaterequerysuggested.aspx">CommandManager.InvalidateRequerySuggested</a> to dirty the commands registered with the <a href="http://msdn.microsoft.com/en-us/library/ms616838(v=VS.90).aspx">CommandManager</a> when an error is raised, which is used in turn to enable/disable the Save button on the form (as it is bound to a Command, so is only enabled if the Command returns <strong>CanExecute</strong> as true)</p>
<p>CommandManager isn&#8217;t implemented in Silverlight 4 at present, so we use <strong>RaiseCanExecuteChanged</strong> directly on our SaveCommand instead. To enable this, I added two extra methods to Josh&#8217;s RelayCommand class: <strong>OnCanExecuteChanged</strong> and <strong>RaiseCanExecutedChanged</strong>, using code from an example at: <a href="http://www.silverlightshow.net/items/Silverlight-4-How-to-Command-Control.aspx">http://www.silverlightshow.net/items/Silverlight-4-How-to-Command-Control.aspx</a></p>
<p>This enabled or disabled the Save button in the View as appropriate, however I wanted the validation error messages to match the WPF sample. To do this, I restyled the TextBox and ComboBox controls in the View to remove the validation tooltip, by clearing out the <strong>ValidationToolTipTemplate</strong> control template.</p>
<p>Then I got the validation messages displaying in TextBlocks under each control by changing the binding Josh was using from: <strong>{Binding Path=(Validation.Errors).CurrentItem}</strong> to: <strong>{Binding (Validation.Errors)[0].ErrorContent}</strong> instead.</p>
<p>The last part was to get the validation on the TextBoxes to fire per keypress, rather than just when they lose focus. In WPF, you use: <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.updatesourcetrigger.aspx">UpdateSourceTrigger=PropertyChanged</a> to achieve this, however that doesn&#8217;t exist in Silverlight 4. There are a few posts on different ways of how to simulate this in Silverlight, but I liked the approach of Thomas Claudius Huber: <a href="http://www.thomasclaudiushuber.com/blog/2009/07/17/here-it-is-the-updatesourcetrigger-for-propertychanged-in-silverlight/">http://www.thomasclaudiushuber.com/blog/2009/07/17/here-it-is-the-updatesourcetrigger-for-propertychanged-in-silverlight/</a> best.</p>
<p>After attaching <strong>helpers:BindingUpdateHelper.UpdateSourceOnChange=&quot;True&quot;</strong> to each TextBox, they validated on each keypress, and all was good.</p>
      <div  class="img " style="width:467px;">
                <a
          href="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_4.png"
          title="Validation"
          
        ><img src="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_4.png" alt="Validation" width="467" height="441" title="Click to enlarge" /></a>
        <div style="width:100%;">Validation</div>
      </div>
<p>&#160;</p>
<h2>Issue Five: Unit Tests!</h2>
<p>Josh kindly included quite comprehensive unit tests in his sample project, so I wanted to get them working in the Silverlight version as well.</p>
<p>I started off with a standard C# Unit Test project, and copied the tests across and updated any namespaces. I also needed to tweak the tests which verify the CurrentItem property of the CollectionViewSource.</p>
<p>Attempting to run the tests resulted in a <strong>FileNotFoundException</strong>: &quot;<em>System.IO.FileNotFoundException: Could not load file or assembly &#8216;System.Xml.Linq, Version=2.0.5.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35&#8242; or one of its dependencies. The system cannot find the file specified</em>&quot;. At this point I was using Linq to XML (although refactored it out later on, so the project no longer needs it), and wanted to figure out what the problem was.</p>
<p>Turns out that the Unit Test project was using the version 4.0 <strong>System.Xml.Linq.dll</strong>, and so there was a mismatch between the versions. The quick solution was to hack the .csproj file (<em>Right click on the project in Visual Studio -&gt; Unload Project -&gt; Right click again and choose Edit -&gt; make your changes and save -&gt; then Right click and choose Reload</em>) to give a HintPath to the reference to point it to the Silverlight version like so:</p>
<p>&lt;Reference Include=&quot;System.Xml.Linq&quot;&gt;   <br />&#160; &lt;HintPath&gt;$(ProgramFiles)\Microsoft SDKs\Silverlight\v4.0\Libraries\Client\System.Xml.Linq.dll&lt;/HintPath&gt;    <br />&lt;/Reference&gt;</p>
<p>After fixing that, most of the tests passed, apart from any that were using the <strong>CustomerRepository</strong>. This turned out to be an issue with the <strong>GetResourceStream</strong> method, which uses <a href="http://msdn.microsoft.com/en-us/library/cc190632(VS.95).aspx">Application.GetResourceStream</a> to load in the <strong>customers.xml</strong> data file. When running via the Unit Tests, this was throwing a <strong>DllNotFoundException</strong>: &quot;<em>Unable to load DLL &#8216;agcore&#8217;: The specified module could not be found</em>&quot;, as the Silverlight process wasn&#8217;t running, so the Application class couldn’t be accessed.</p>
<p>The quick solution to get the tests passing was to catch the DllNotFoundException and load the resource file using a standard <a href="http://msdn.microsoft.com/en-us/library/system.io.streamreader.aspx">StreamReader</a> instead. A better long term solution would be to use something like Dependency Injection or Mocks instead.</p>
<p>The tests all passed fine after this, so I created a Silverlight Unit Test project as well to test them in there. They passed fine in this as well. You can run the tests by right clicking the <strong>SilverlightUnitTestsTestPage.aspx</strong> page in the <strong>MVVMSilverlightDemoApp.Web</strong> project and choosing <strong>View In Browser</strong>. This will launch a browser window with a Silverlight test harness which will run all the unit tests and show the results.</p>
      <div  class="img " style="width:365px;">
                <a
          href="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_5.png"
          title="Unit Tests"
          
        ><img src="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/image_5.png" alt="Unit Tests" width="365" height="561" title="Click to enlarge" /></a>
        <div style="width:100%;">Unit Tests</div>
      </div>
<p>So, that&#8217;s it. You can download the solution below and have a play around and compare it to <a href="http://msdn.microsoft.com/en-us/magazine/dd419663.aspx">Josh&#8217;s WPF original</a>. Hope it helps.</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:fb3a1972-4489-4e52-abe7-25a00bb07fdf:49088040-f7f4-4e90-b9fc-7ea40453df4e" class="wlWriterEditableSmartContent">
<p> <a href="http://edventuro.us/wp-content/uploads/PortingaWPFAppwiththeModelViewViewModelD_EB9D/MVVMSilverlightDemoApp.zip">MVVMSilverlightDemoApp.zip</a></p>
</div>
      <div  class="img " style="width:0px;">
        <a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fedventuro.us%2f2010%2f03%2fporting-a-wpf-app-with-the-model-view-viewmodel-design-pattern-to-silverlight-4%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fedventuro.us%2f2010%2f03%2fporting-a-wpf-app-with-the-model-view-viewmodel-design-pattern-to-silverlight-4%2f" alt="kick it on DotNetKicks.com"   title="Click to enlarge" /></a>
        
      </div>
]]></content:encoded>
			<wfw:commentRss>http://edventuro.us/2010/03/porting-a-wpf-app-with-the-model-view-viewmodel-design-pattern-to-silverlight-4/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Sample page using the AutoScalingTextBlock</title>
		<link>http://edventuro.us/2010/03/sample-page-using-the-autoscalingtextblock/</link>
		<comments>http://edventuro.us/2010/03/sample-page-using-the-autoscalingtextblock/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 16:11:00 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[AutoScalingTextBlock]]></category>
		<category><![CDATA[Sample]]></category>

		<guid isPermaLink="false">http://edventuro.us/?p=13</guid>
		<description><![CDATA[Here’s a sample page using the AutoScalingTextBlock referred to in the previous post (An Auto Scaling TextBlock for Silverlight).
Use the GridSplitter controls (grey lines) at the right and bottom of the grid to change the size of the TextBlocks and see the font size change up and down, depending on the ‘ScalingMode’ setting of each [...]]]></description>
			<content:encoded><![CDATA[<p>Here’s a sample page using the AutoScalingTextBlock referred to in the previous post (<a href="http://edventuro.us/?p=9">An Auto Scaling TextBlock for Silverlight</a>).</p>
<p>Use the GridSplitter controls (grey lines) at the right and bottom of the grid to change the size of the TextBlocks and see the font size change up and down, depending on the ‘ScalingMode’ setting of each AutoScalingTextBlock, or resize the page to also see it in action.</p>
<p><span id="more-13"></span></p>
<style type="text/css">
    #silverlightControlHost {
	    height: 100%;
	    text-align:center;
    }
</style>
<div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="500"><param name="source" value="/wp-content/uploads/AnAutoResizingTextBlockforSilverlight_CCB0/AutoScalingControlsSample.xap"/><param name="background" value="white" /><param name="minRuntimeVersion" value="3.0.40624.0" /><param name="autoUpgrade" value="true" /><a href="http://go.microsoft.com/fwlink/?LinkID=149156&#038;v=3.0.40624.0" style="text-decoration:none"><br />
 			       <div  class="img " style="width:0px;">
                <a
          href="http://go.microsoft.com/fwlink/?LinkId=108181"
          title=""
          
        ><img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight"   title="Click to enlarge" /></a>
        
      </div><br />
		  </a><br />
	    </object></div>
]]></content:encoded>
			<wfw:commentRss>http://edventuro.us/2010/03/sample-page-using-the-autoscalingtextblock/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>An Auto Scaling TextBlock for Silverlight</title>
		<link>http://edventuro.us/2010/03/an-auto-scaling-textblock-for-silverlight/</link>
		<comments>http://edventuro.us/2010/03/an-auto-scaling-textblock-for-silverlight/#comments</comments>
		<pubDate>Tue, 09 Mar 2010 15:50:31 +0000</pubDate>
		<dc:creator>Ed</dc:creator>
				<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[AutoScalingTextBlock]]></category>
		<category><![CDATA[Controls]]></category>
		<category><![CDATA[TextBlock]]></category>

		<guid isPermaLink="false">http://edventuro.us/?p=9</guid>
		<description><![CDATA[During a recent Silverlight project which required extensive localisations into eight different European languages, I discovered just how much text length can vary between cultures. This caused a couple of issues where there was a limited area for a specific piece of text to fit within, which would look fine in English, but then would [...]]]></description>
			<content:encoded><![CDATA[<p>During a recent Silverlight project which required extensive localisations into eight different European languages, I discovered just how much text length can vary between cultures. This caused a couple of issues where there was a limited area for a specific piece of text to fit within, which would look fine in English, but then would not fit in a different language and would be cut off.</p>
<p>I thought this would be a good idea for a custom control, and so have written an AutoScalingTextBlock control.</p>
<p>It’s a simple text control (based on ‘ContentControl’) that shrinks or expands the font of the text to display all of the text in the preferred size of the TextBlock. See it in action: <a href="http://edventuro.us/2010/03/sample-page-using-the-autoscalingtextblock/">http://edventuro.us/2010/03/sample-page-using-the-autoscalingtextblock/</a></p>
<p>While deciding how to get started, I came across an excellent TextTrimming TextBlock on Robby Ingebretsen’s site: <a href="http://blog.nerdplusart.com/archives/texttrimming-textblock-for-silverlight">http://blog.nerdplusart.com/archives/texttrimming-textblock-for-silverlight</a> which I used as a basis, and so am releasing my control under the same MIT license that he used. I hope it comes in handy for someone.</p>
<h2>AutoScalingTextBlock:</h2>
<h3>Dependency Properties:</h3>
<ul>
<li><strong>MinFontSize</strong>: This is the smallest size the font will be reduced to. Defaults to 8pt.</li>
<li><strong>MaxFontSize</strong>: This is the largest size the font will be increased to. Defaults to 20.</li>
<li><strong>ScalingMode</strong>: This controls if the font size should be scaled only up, or down, or both ways to fit the text within the boundaries of the textbox.  Defaults to BothWays.</li>
<li><strong>StepSize</strong>: This is the point size the font will be increased or decreased by each iteration until the text fits the desired size. Higher amounts will require fewer iterations, so will be faster, but the changes will be more abrupt. Defaults to 0.5.</li>
</ul>
<p>Download the control: <a href="http://edventuro.us/wp-content/uploads/AnAutoResizingTextBlockforSilverlight_CCB0/AutoScalingTextBlock.cs">AutoScalingTextBlock.cs</a> or a sample solution with examples in the Page.xaml file: <a href="http://edventuro.us/wp-content/uploads/AnAutoResizingTextBlockforSilverlight_CCB0/AutoScalingControls.zip">AutoScalingControls.zip</a>.  Free to use under the MIT licence.</p>
      <div  class="img " style="width:0px;">
        <a href="http://www.dotnetkicks.com/kick/?url=http%3a%2f%2fedventuro.us%2f2010%2f03%2fan-auto-scaling-textblock-for-silverlight%2f"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http%3a%2f%2fedventuro.us%2f2010%2f03%2fan-auto-scaling-textblock-for-silverlight%2f" alt="kick it on DotNetKicks.com"   title="Click to enlarge" /></a>
        
      </div>
]]></content:encoded>
			<wfw:commentRss>http://edventuro.us/2010/03/an-auto-scaling-textblock-for-silverlight/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

