<?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>Belfry Images &#187; C#</title>
	<atom:link href="http://blog.belfryimages.com.au/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.belfryimages.com.au</link>
	<description>Ben Scott's personal blog</description>
	<lastBuildDate>Fri, 20 Aug 2010 22:31:26 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Extract method to class refactoring</title>
		<link>http://blog.belfryimages.com.au/2010/08/21/extract-method-to-class-refactoring/</link>
		<comments>http://blog.belfryimages.com.au/2010/08/21/extract-method-to-class-refactoring/#comments</comments>
		<pubDate>Fri, 20 Aug 2010 22:31:26 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=366</guid>
		<description><![CDATA[The Extract Method refactoring is a basic refactoring technique where a part of a method is extracted out into a new method. This is used to: Simplify a complex method, Promote DRY, and Make testing easier Here&#8217;s my Union-required contrived example: interface IFoo { } interface IFooRepository { IEnumerable&#60;IFoo&#62; GetFoos(); } class FooProcessor { IFooRepository [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://www.refactoring.com/catalog/extractMethod.html">Extract Method</a> refactoring is a basic refactoring technique where a part of a method is extracted out into a new method. This is used to:</p>
<ul>
<li>Simplify a complex method,</li>
<li>Promote DRY, and</li>
<li>Make testing easier</li>
</ul>
<p>Here&#8217;s my Union-required contrived example:</p>
<pre class="brush:c#">
interface IFoo { }
interface IFooRepository
{
    IEnumerable&lt;IFoo&gt; GetFoos();
}

class FooProcessor
{
    IFooRepository FooRepository { get; set; }
    public FooProcessor(IFooRepository fr)
    {
        this.FooRepository = fr;
    }

    public IEnumerable&lt;IFoo&gt; GetProcessedFoos()
    {
        foreach (var foo in this.FooRepository.GetFoos())
        {
            // Do some processing on foo
            // ...
            // ...

            yield return foo;
        }
    }
}
</pre>
<p>The inside of the loop in <code>FooProcessor.GetProcessedFoos()</code> might suit being extracted into a new method:</p>
<pre class="brush:c#">
public IEnumerable&lt;IFoo&gt; GetProcessedFoos()
{
    foreach (var foo in this.FooRepository.GetFoos())
    {
        yield return this.GetProcessedFoo(foo);
    }
}

public IFoo GetProcessedFoo(IFoo foo)
{
    // Do some processing on foo
    // ...
    // ...
    return foo;
}
</pre>
<p>Now I can test the foo processing code without having to worry about setting up an <code>IFooRepository</code> mock just to pass in a single <code>IFoo</code>. Unfortunately the <code>FooProcessor</code> class still has the <code>IFooRepository</code> dependency, which I could work around by passing <code>null</code> to the constructor:</p>
<pre class="brush:c#">
var fooProcessor = new FooProcessor(null);
// test fooProcessor.GetProcessedFoo(...)
</pre>
<p>But that isn&#8217;t very clear, and when there are lots of tests and dependencies things can get very, very silly. Extracting the method into a separate class can solve the problem:</p>
<pre class="brush:c#">
public IEnumerable&lt;IFoo&gt; GetProcessedFoos()
{
    foreach (var foo in this.FooRepository.GetFoos())
    {
        yield return new GetProcessedFooMethod().Execute(foo);
    }
}

public class GetProcessedFooMethod
{
    public IFoo Execute(IFoo foo)
    {
        // Do some processing on foo
        // ...
        // ...
        return foo;
    }
}
</pre>
<p>Now the method can be tested directly without concerning <code>FooProcessor</code>&#8216;s dependencies:</p>
<pre class="brush:c#">
var getProcessedFooMethod = new FooProcessor.GetProcessedFooMethod();
// test via getProcessedFooMethod.Execute(foo)
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/08/21/extract-method-to-class-refactoring/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ditch DI frameworks, get control back and improve testability</title>
		<link>http://blog.belfryimages.com.au/2010/08/20/ditch-di-frameworks-get-control-back-and-improve-testability/</link>
		<comments>http://blog.belfryimages.com.au/2010/08/20/ditch-di-frameworks-get-control-back-and-improve-testability/#comments</comments>
		<pubDate>Thu, 19 Aug 2010 23:11:57 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=355</guid>
		<description><![CDATA[Not long ago I started using Ninject to inject dependencies into the day job&#8217;s in-house system. Up until then all the dependencies in the system were strongly bound, often created within a method. Not surprisingly this made testing this old code (also something only started in the last year) quite difficult. So using Ninject was [...]]]></description>
			<content:encoded><![CDATA[<p>Not long ago I started using <a href="http://ninject.org/">Ninject</a> to inject dependencies into <a href="http://capinvest.com.au">the day job&#8217;s</a> in-house system. Up until then all the dependencies in the system were strongly bound, often created within a method. Not surprisingly this made testing this old code (also something only started in the last year) quite difficult. So using Ninject was a pretty painless way of loosening these strongly bound dependencies (and the way I thought about dependencies).</p>
<p>I pretty quickly found an issue with this approach. Say I&#8217;m integration testing <code>B.MethodToTest()</code> in the following code:</p>
<pre class="brush:c#">
interface IInterfaceForA
{
    string DoSomethingInA(string s);
}
class A
{
    [Inject]
    public ISomeInnerDependency SomeInnerDependency { get; set; }

    public string DoSomethingInA(string s)
    {
        this.SomeInnerDependency.DoBlah(s);
        // ...
    }
}

class B
{
    [Inject]
    public IInterfaceForA A { get; set; }

    public string MethodToTest(string s)
    {
        this.A.DoSomethingInA(s);
        // ...
    }
}
</pre>
<p>So class <code>B</code> has a dependency on <code>IInterfaceForA</code> (which Ninject will inject with an instance of <code>A</code>), and class <code>A</code> has a dependency on <code>ISomeInnerDependency</code>. Now say that the implementation of <code>ISomeInnerDependency</code> that gets injected hits a database that doesn&#8217;t exist during the test and dies. I&#8217;m testing <code>B.MethodToTest()</code> and its interaction with <code>A.DoSomethingInA()</code> but I don&#8217;t know beforehand of <code>A</code>&#8216;s dependency on <code>ISomeInnerDependency</code>, so when I run tests I&#8217;ll get unexpected failures which will depend on how I&#8217;ve set up Ninject prior to the test:</p>
<ul>
<li>if the test setup for Ninject doesn&#8217;t inject <code>ISomeInnerDependency</code> at all, I&#8217;ll get <code>NullReferenceException</code>s</li>
<li>if Ninject is injecting the production implementation of <code>ISomeInnerDependency</code>, any type of error at all from just about anywhere in <code>ISomeInnerDependency</code>&#8216;s implementation&#8217;s call stack</li>
</ul>
<p>Either way I&#8217;m getting errors from code that I didn&#8217;t even know about beforehand. I can resolve this by doing something like injecting a mock into <code>A.SomeInnerDependency</code> but there&#8217;s no way I could have known about the dependency before spelunking into the <code>A</code> class.</p>
<p>If the method I&#8217;m testing happens to have five dependencies, and some of those dependencies have more dependencies, my workflow devolves into: Compile, Run test, Watch fail, Sort through call stack, Find dependency, Figure out some way for Ninject to inject some harmless stub, Repeat for next nested dependency. I&#8217;m spending more time finding, stubbing, and injecting dependencies then I am writing tests and production code combined.
<p>There is an argument that the code I&#8217;m testing is too complex and should be refactored. Fair enough, and my new code is much cleaner now that I&#8217;m thinking about testability now, but:</p>
<ul>
<li>This is an integration test</li>
<li>The code base has three years worth of (my) beginner crap thrown in</li>
<li>I should be able to inject dependencies to existing code to <em>increase testability</em> and <em>increase my efficiency</em>, not to have to struggle with the DI framework and seemingly random run-time errors</li>
<li>There is one developer, and this is an in-house business application that services 15 staff and 300 clients. No resources, no time.</li>
<li>An oversight meant that Ninject didn&#8217;t inject some dependencies that made it into production. Nasty.</li>
</ul>
<p>In short, Ninject ended up causing more problems than it solved. Time to take the power back:</p>
<pre class="brush: c#">
interface IInterfaceForA
{
    string DoSomethingInA(string s);
}
class A
{
    public ISomeInnerDependency SomeInnerDependency { get; set; }

    public A(ISomeInnerDependency someInnerDependency)
    {
        this.SomeInnerDependency = someInnerDependency;
    }

    public string DoSomethingInA(string s)
    {
        this.SomeInnerDependency.DoBlah(s);
        // ...
    }
}

class B
{
    public IInterfaceForA A { get; set; }

    public B(IInterfaceForA a)
    {
        this.A = a;
    }

    public string MethodToTest(string s)
    {
        this.A.DoSomethingInA(s);
        // ...
    }
}
</pre>
<p>I&#8217;ve done two things here. First I dropped Ninject. Then I added constructors to <code>A</code> and <code>B</code> so that the dependencies are explicit. To create an instance of <code>B</code> I now have to provide the dependencies up-front rather than configure them beforehand (and hope I&#8217;ve covered everything):</p>
<pre class="brush:c#">
var b = new B(new A(new InnerDependencyMuchoDatabase("database configuration...")));
</pre>
<p>In the test for <code>B.MethodToTest()</code> I can just pass a stub to <code>A</code>:</p>
<pre class="brush:c#">
var b = new B(new A(stubInnerDependency));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/08/20/ditch-di-frameworks-get-control-back-and-improve-testability/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Accessing anonymous object properties using reflection</title>
		<link>http://blog.belfryimages.com.au/2010/04/19/accessing-anonymous-object-properties-using-reflection/</link>
		<comments>http://blog.belfryimages.com.au/2010/04/19/accessing-anonymous-object-properties-using-reflection/#comments</comments>
		<pubDate>Sun, 18 Apr 2010 22:38:50 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=304</guid>
		<description><![CDATA[Anonymous objects are a way to create strongly typed objects without having to declare a class or struct in C# 3.5 and above. Declaring an anonymous object is easy: var breakfast = new { Cereal = "High fibre", Coffee = "Latte", Bacon = "Crispy" }; In the scope of the object&#8217;s declaration, accessing the properties [...]]]></description>
			<content:encoded><![CDATA[<p>Anonymous objects are a way to create strongly typed objects without having to declare a class or struct in C# 3.5 and above. Declaring an anonymous object is easy:</p>
<pre class="brush:c#">
var breakfast = new
{
    Cereal = "High fibre",
    Coffee = "Latte",
    Bacon = "Crispy"
};
</pre>
<p>In the scope of the object&#8217;s declaration, accessing the properties of <code>breakfast</code> is as simple as <code>breakfast.Cereal</code>. However accessing the properties outside of that scope is not as simple. Say we have an object <code>ben</code> with a method <code>Eat(object meal)</code>. Within <code>ben.Eat()</code> we can&#8217;t do something directly with <code>meal.Coffee</code> because <code>Coffee</code> isn&#8217;t known in <code>ben.Eat()</code>&#8216;s scope.</p>
<p>Getting a property value using reflection is pretty basic but takes a couple of steps. There are much more advanced uses of reflection that allow access to hidden properties, fields and methods, but picking public properties is probably the easiest case. The following method returns the value of a public property of an object. This could be used on an anonymous object, or on any other class of object.</p>
<pre class="brush:c#">
using System.Reflection;
...
object GetPropertyValue(object o, string propertyName)
{
    var prop = o.GetType().GetProperty(propertyName);
    if (prop == null) return null;
    return prop.GetValue(o, null);
}
...
var cereal = GetPropertyValue(breakfast, "Cereal");
Assert.That(cereal, Is.EqualTo("High fibre"));
</pre>
<p><code>prop</code> is a PropertyInfo object that lets the value of a property be retrieved via reflection. The same method can be used to get a dictionary of [property name, value] from an anonymous object:</p>
<p><code>prop</code> is a PropertyInfo object that lets the value of a property be retrieved via reflection. The same method can be used to get a dictionary of [property name, value] from an anonymous object:</p>
<pre class="brush:c#">
IDictionary&lt;string, object&gt; ObjectToDictionary(object o)
{
    var dict = o.GetType().GetProperties().ToDictionary(
        prop => prop.Name, prop => prop.GetValue(o, null)
            );
    return dict;
}
</pre>
<p>This sets up a dictionary where the key is the name of the property, and the value is (ahem) the value of the property:</p>
<pre class="brush:c#">
var breakfastDictionary = ObjectToDictionary(breakfast);
Assert.That(breakfastDictionary.Count, Is.EqualTo(3));
Assert.That(breakfastDictionary["Coffee"], Is.EqualTo("Latte"));
</pre>
<p>Using anonymous objects and reflection is a bit slower to execute than using strongly-typed objects, but once the methods are in place to access the properties, the savings in developer time can be great. Leaving more time for breakfast. Speaking of which, I&#8217;m late for work.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/04/19/accessing-anonymous-object-properties-using-reflection/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Extension Methods in C#</title>
		<link>http://blog.belfryimages.com.au/2010/03/20/extension-methods-in-c/</link>
		<comments>http://blog.belfryimages.com.au/2010/03/20/extension-methods-in-c/#comments</comments>
		<pubDate>Sat, 20 Mar 2010 03:22:43 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=299</guid>
		<description><![CDATA[This is pretty basic and has been around for a while but I always forget about it until it&#8217;s too late. From C# 3.0 onwards we&#8217;ve been able to declare methods that extend a class. There&#8217;s no magic, the method doesn&#8217;t actually get added to the class and can&#8217;t access the internals of the class, [...]]]></description>
			<content:encoded><![CDATA[<p>This is pretty basic and has been around for a while but I always forget about it until it&#8217;s too late. From C# 3.0 onwards we&#8217;ve been able to declare methods that extend a class. There&#8217;s no magic, the method doesn&#8217;t actually get added to the class and can&#8217;t access the internals of the class, it&#8217;s just a shorthand way of making a static call.</p>
<p>The extension method is declared in a static class:
<pre class="brush:c#">
public static class PimpMyStringExtension
{
    public static string Pimp(this string s)
    {
        return s + " is pimped out";
    }
}
</pre>
<p>Adding the <code>this</code> keyword to <code>Pimp</code>&#8216;s <code>string s</code> argument is what indicates that <code>Pimp</code> is an extension method to the <code>string</code> class. The <code>Pimp</code> method can now be called against any string:</p>
<pre class="brush:c#">
Assert.That("test".Pimp(), Is.EqualTo("test is pimped out"));
</pre>
<p>As long as the <code>PimpMyStringExtension</code> is accessible to the consuming code, the <code>String</code> gets the <code>Pimp()</code> method added. <code>"test".Pimp()</code> actually just calls the static method under the covers, which is actually still an option:</p>
<pre class="brush:c#">
Assert.That(PimpMyStringExtension.Pimp("test"), Is.EqualTo("test is pimped out"));
</pre>
<p>Extra arguments can be added to the extension method as well:</p>
<pre class="brush:c#">
 public static string Pimp(this string s, int i)
{
    return s + " has been pimped with " + i;
}
...
Assert.That("test".Pimp(7), Is.EqualTo("test has been pimped with 7"));
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/03/20/extension-methods-in-c/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection inside a loop vs via a factory &#8211; part 2</title>
		<link>http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory-part-2/</link>
		<comments>http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory-part-2/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 12:18:14 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=272</guid>
		<description><![CDATA[In my last post I compared calling Ninject inside a loop during object contruction vs calling Ninject once and using a factory class to return a singleton. That wasn&#8217;t an entirely fair comparison as Ninject was creating a new instance of the injected class every time, which I thought may be part of the cause [...]]]></description>
			<content:encoded><![CDATA[<p>In my <a href="http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory/">last post</a> I compared calling <a href="http://ninject.org/">Ninject</a> inside a loop during object contruction vs calling Ninject once and using a factory class to return a singleton. That wasn&#8217;t an entirely fair comparison as Ninject was creating a new instance of the injected class every time, which I thought may be part of the cause of the difference in performance. So I&#8217;ve changed my test a bit so that Ninject uses a singleton as well.</p>
<p>Originally the Ninject kernel binding was like this:</p>
<pre class="brush: csharp">
NinjectContainer.Kernel.Bind&lt;IAdditionProvider&gt;().To&lt;AdditionProvider&gt;();
</pre>
<p>That tells Ninject to create a new instance of <code>AdditionProvider</code> every time. To get it to use the same instance &#8211; in effect a singleton &#8211; I changed the binding to this:</p>
<pre class="brush: csharp">
NinjectContainer.Kernel.Bind&lt;IAdditionProvider&gt;().ToConstant(new AdditionProvider());
</pre>
<p>I expected to see a huge performance gain, and feel like an idiot. There was a bit of a gain:</p>
<p><a href="http://blog.belfryimages.com.au/wp-content/uploads/2010/02/Untitled.png"><img src="http://blog.belfryimages.com.au/wp-content/uploads/2010/02/Untitled.png" alt="" title="Injection using a singleton" width="229" height="195" class="alignnone size-full wp-image-273" /></a></p>
<p>That&#8217;s roughly 8 seconds (or 12%) less then the 1m5s taken the first time around. So there&#8217;s a good gain to be had using <code>ToConstant()</code> to avoid creating unnecessary instances of the injected class, but still nothing like the benefits of only directly using Ninject outside of the loop.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory-part-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Dependency Injection inside a loop vs via a factory</title>
		<link>http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory/</link>
		<comments>http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory/#comments</comments>
		<pubDate>Fri, 05 Feb 2010 15:36:02 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=263</guid>
		<description><![CDATA[I may have gone overboard with implementing dependency injection using Ninject on a project at work. I ended up with multiple calls to the kernel when creating each object. Worse yet I&#8217;ve used the [Inject] attribute to implement the binding, building up hundreds of dependencies on the Ninject library. At the time this seemed to [...]]]></description>
			<content:encoded><![CDATA[<p>I may have gone overboard with implementing dependency injection using <a href="http://ninject.org/">Ninject</a> on a project at work. I ended up with multiple calls to the kernel when creating each object. Worse yet I&#8217;ve used the <code>[Inject]</code> attribute to implement the binding, building up hundreds of dependencies on the Ninject library. At the time this seemed to make implementing things easier, especially as this was the first time I had used a dependency injection library, and I didn&#8217;t see a problem with a dependency on what seems like a core component.</p>
<p>I separated out 30 or so repositories, set up a heap of fakes, hooked up a handful of tests, and jumped into implementing the latest feature. Everything went well in development, I deployed, and all was shiny. Then the trouble started.</p>
<p>First the users started complaining about speed. Some operations were taking 10-20 times as long to run as before. That was because of calls to Ninject happening whenever many objects were being created, and inside of loops. Then some older Winforms components turned out to crash in the designer. That was due to the Ninject kernel not being set up when the component is executed by the designer &#8211; the new dependency on Ninject was failing. Then I read <a href="http://blog.objectmentor.com/articles/2010/01/17/dependency-injection-inversion" title="Dependency Injection Inversion - Object Mentor blog">an article by Bob Martin</a> and several of his tweets on the subject where he talks about the dependency framework itself becoming a dependency. Got that right.
<p>I decided to replace the direct dependency injection via Ninject with a factory. This way the factory is the only place with the dependency on Ninject, and has the option of returning a mock if there is Ninject isn&#8217;t configured (to deal with the designer issues). It also lets me inject the dependency only once and reuse the result.</p>
<p>I set up a simple test to see what effect moving the dependency injection out of the loop would have on the speed. The first consumer of the test is has the DI on construction:</p>
<pre class="brush: csharp">
class InjectionTester
{
    [Inject] public IAdditionProvider Adder { get; set; }
    public int DoAdd(int a, int b) { return Adder.Add(a, b); }
}
...
// test using injection in the loop
for (int i = 0; i &lt; 1000; i++)
{
    for (int j = 0; j &lt; 1000; j++)
    {
        var tester = NinjectContainer.Kernel.Get&lt;InjectionTester&gt;();
        tester.DoAdd(i, j);
    }
}
</pre>
<p>The second consumer of the test uses a factory to get the dependency:</p>
<pre class="brush: csharp">
class AdditionProviderFactory
{
    public static AdditionProviderFactory Instance = new AdditionProviderFactory();

    IAdditionProvider additionProvider;
    object additionProviderLock = new object();
    public IAdditionProvider AdditionProvider
    {
        get
        {
            lock (additionProviderLock)
            {
                additionProvider = additionProvider ?? NinjectContainer.Kernel.Get&lt;IAdditionProvider&gt;();
            }
            return additionProvider;
        }
    }
}
class FactoryTester
{
    IAdditionProvider Adder = AdditionProviderFactory.Instance.AdditionProvider;
    public int DoAdd(int a, int b) { return Adder.Add(a, b); }
}
...
// test using the factory
for (int i = 0; i &lt; 1000; i++)
{
    for (int j = 0; j &lt; 1000; j++)
    {
        var tester = new FactoryTester();
        tester.DoAdd(i, j);
    }
}
</pre>
<p>The results are pretty impressive (looping a million times):</p>
<p><a href="http://blog.belfryimages.com.au/wp-content/uploads/2010/02/di_vs_factory_benchmark.png"><img src="http://blog.belfryimages.com.au/wp-content/uploads/2010/02/di_vs_factory_benchmark.png" alt="" title="Benchmarking DI vs a factory" width="234" height="197" class="alignnone size-full wp-image-262" /></a></p>
<p>Thinking about it now it&#8217;s pretty obvious that DI is going to be a bit expensive, but seriously, using a factory is over <em>200 times faster</em>. That should keep em quiet.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/02/06/dependency-injection-inside-a-loop-vs-via-a-factory/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Injecting Rhino Mocks with Ninject</title>
		<link>http://blog.belfryimages.com.au/2010/01/20/injecting-rhino-mocks-with-ninject/</link>
		<comments>http://blog.belfryimages.com.au/2010/01/20/injecting-rhino-mocks-with-ninject/#comments</comments>
		<pubDate>Wed, 20 Jan 2010 13:36:15 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Tutorials]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=243</guid>
		<description><![CDATA[So today I hit a hat trick. I needed to test a class that had an injected dependency, and needed some functionality that I didn&#8217;t want to add to a fake and would rather isolate to the test. I needed to use a mocking framework. This is my first time using mocks (and only my [...]]]></description>
			<content:encoded><![CDATA[<p>So today I hit a <a href="http://en.wikipedia.org/wiki/Hat-trick">hat trick</a>. I needed to test a class that had an injected dependency, and needed some functionality that I didn&#8217;t want to add to a fake and would rather isolate to the test. I needed to use a mocking framework. This is my first time using mocks (and only my second week of dependency injection) so this may not use best practices, but this _is_ a blog after all.</p>
<p>I&#8217;m using <a href="http://github.com/enkari/ninject">Ninject 2</a> for dependency injection, <a href="http://www.nunit.org/index.php">NUnit 2.5.3</a> for unit testing, and <a href="http://www.ayende.com/projects/rhino-mocks.aspx">Rhino Mocks 3.6</a> for mocking. NUnit has a mocking framework built in but it doesn&#8217;t use strong typing, which I think was causing problems with Ninject.</p>
<p>What I&#8217;m really showing here is an example of how to inject a dynamically declared mock instead of a concrete fake. The fact that it is in the context of a test is actually irrelevant, but using mocks and fakes are obviously important in testing to reduce the complexity of the test.</p>
<p>Initially I&#8217;m using the default <code>ConcreteFoo</code> implementation of <code>IFoo</code> in the test. This test fails as intended:</p>
<pre class="brush: c#">
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Ninject;
using NUnit.Framework;
using Rhino.Mocks;

namespace Trifecta
{
    public interface IFoo
    {
        string Name { get; }
    }
    public class ConcreteFoo : IFoo
    {
        public string Name { get { return &quot;You don't want to see me&quot;; } }
    }

    public class FooConsumer
    {
        [Inject] public IFoo Foo { get; set; }

        public FooConsumer() {}
    }

    [TestFixture]
    public class FooConsumerTestFixture
    {
        IKernel Kernel { get; set; }

        [SetUp]
        public void SetUp()
        {
            // This is the standard setup that will need to be overridden in the
            // test.
            Kernel = new StandardKernel();
            Kernel.Bind&lt;IFoo&gt;().To&lt;ConcreteFoo&gt;();
        }

        [Test]
        public void FooConsumerGetsTheFoo()
        {
            // This test depends on a specific behaviour in IFoo, but ConcreteFoo
            // is going disappoint right now.
            var fooConsumer = Kernel.Get&lt;FooConsumer&gt;();

            Assert.That(fooConsumer.Foo.Name, Is.EqualTo(&quot;The foo for you&quot;));
        }
    }
}
</pre>
<p>Settting up and binding the mock is all done in the test method. The mock <code>IFoo</code> instance is created, and the functionality that the test requires is added. IFoo is then bound to a delegate which returns the mock instance. The binding has a condition that causes the mock binding to be used rather than the <code>ConcreteFoo</code> binding, this seems to be easier then setting up the kernel from scratch for the test (possibly I&#8217;m just missing how to rebind).</p>
<pre class="brush: c#">
[Test]
public void FooConsumerGetsTheFoo()
{
		// Create a mock implementation of IFoo that has the behaviour the test requires
		var mocks = new MockRepository();
		var mockFoo = mocks.StrictMock&lt;IFoo&gt;();
		Expect.Call(mockFoo.Name).Return(&quot;The foo for you&quot;);
		mocks.ReplayAll();

		// Bind the mock when injecting IFoo into FooConsumer. This overrides the binding
		// created in SetUp()
		Kernel.Bind&lt;IFoo&gt;().ToMethod(context =&gt; mockFoo).WhenInjectedInto&lt;FooConsumer&gt;();

		// fooConsumer's Foo should now be the mock IFoo created above
		var fooConsumer = Kernel.Get&lt;FooConsumer&gt;();

		Assert.That(fooConsumer.Foo.Name, Is.EqualTo(&quot;The foo for you&quot;));
}
</pre>
<p>The test should now pass.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2010/01/20/injecting-rhino-mocks-with-ninject/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Declaring a class with inheritance and a generic type constraint in C#</title>
		<link>http://blog.belfryimages.com.au/2009/11/13/declaring-a-class-with-inheritance-and-a-generic-type-constraint-in-csharp/</link>
		<comments>http://blog.belfryimages.com.au/2009/11/13/declaring-a-class-with-inheritance-and-a-generic-type-constraint-in-csharp/#comments</comments>
		<pubDate>Fri, 13 Nov 2009 02:50:13 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://blog.belfryimages.com.au/?p=187</guid>
		<description><![CDATA[I&#8217;m writing a generic class that inherits from a base class, implements an interface, and has a type constraint on the generic class. The class inheritance and interface are straightforward, as is the type constraint, but combined together it&#8217;s not obvious how to write this. Any examples of type constraints I could find don&#8217;t have [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m writing a generic class that inherits from a base class, implements an interface, and has a type constraint on the generic class. The class inheritance and interface are straightforward, as is the type constraint, but combined together it&#8217;s not obvious how to write this. Any examples of type constraints I could find don&#8217;t have inheritance or interfaces as well. So, via a bit of trail and error, here is <em>a</em> right way to declare such a class:</p>
<pre class="brush: c#">
public class MyClass&lt;T&gt; :
    BaseClass&lt;T&gt;, IMyInterface
    where T : ClassOfT
{...}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2009/11/13/declaring-a-class-with-inheritance-and-a-generic-type-constraint-in-csharp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ZedGraph &#8211; .NET graph control</title>
		<link>http://blog.belfryimages.com.au/2008/03/28/zedgraph-net-graph-control/</link>
		<comments>http://blog.belfryimages.com.au/2008/03/28/zedgraph-net-graph-control/#comments</comments>
		<pubDate>Fri, 28 Mar 2008 09:56:58 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[UI]]></category>

		<guid isPermaLink="false">http://belfryimages.com.au/2008/03/28/zedgraph-net-graph-control/</guid>
		<description><![CDATA[Today I needed a graphing control, and with a bit of searching found ZedGraph. This has got to be the best open source .NET component I&#8217;ve ever used. All you need to do is reference the .DLL, drop a ZedGraph control onto your form or control, and add some code to load in a data [...]]]></description>
			<content:encoded><![CDATA[<p>Today I needed a graphing control, and with a bit of searching found <a href="http://zedgraph.org">ZedGraph</a>. This has got to be the best open source .NET component I&#8217;ve ever used. All you need to do is reference the .DLL, drop a ZedGraph control onto your form or control, and add some code to load in a data range. It&#8217;s even easier to make a pie chart and the colours, gradients, etc., are all customisable. Out of the box the control automatically has zooming, scaling, printing and exporting features accessible to the user, and it looks nice and clean. There&#8217;s also a ZedGraphWeb control built in which is for use in ASP.NET apps (although I haven&#8217;t tried that out).</p>
<p>There are two concurrent versions for both .NET 1.1 and .NET 2 (which is very handy since I&#8217;m limited to .NET 1.1 at work). The only difference between the versions is apparently use of templates for collections.</p>
<p>There&#8217;s a <a href="http://www.codeproject.com/KB/graphics/zedgraph.aspx">CodeProject article</a> that gives a pile of simple demo code, and the <a href="http://zedgraph.org">main site</a> is a Wiki with what looks like plenty of documentation. The library is licensed under the LGPL license, which means that derivative works must be LGPLed, but as long as the library&#8217;s DLLs are dynamically linked they can be included in commercial software.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2008/03/28/zedgraph-net-graph-control/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Logical XOR operator in C#</title>
		<link>http://blog.belfryimages.com.au/2008/03/04/logical-xor-operator-in-c/</link>
		<comments>http://blog.belfryimages.com.au/2008/03/04/logical-xor-operator-in-c/#comments</comments>
		<pubDate>Tue, 04 Mar 2008 06:46:43 +0000</pubDate>
		<dc:creator>ben</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Programming]]></category>

		<guid isPermaLink="false">http://belfryimages.com.au/2008/03/04/logical-xor-operator-in-c/</guid>
		<description><![CDATA[For reference the logical XOR operator in C# is the same as the bitwise XOR operator: ^. This always gets me because usually the logical boolean operators are like &#038;&#038; and &#124;&#124; versus the bitwise operators (&#038; and &#124;). I guess it&#8217;s the same thing anyway, just a bitwise XOR operation on two booleans. Fascinating.]]></description>
			<content:encoded><![CDATA[<p>For reference the logical XOR operator in C# is the same as the bitwise XOR operator: <strong>^</strong>. This always gets me because usually the logical boolean operators are like &#038;&#038; and || versus the bitwise operators (&#038; and |). I guess it&#8217;s the same thing anyway, just a bitwise XOR operation on two booleans. Fascinating.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.belfryimages.com.au/2008/03/04/logical-xor-operator-in-c/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
