Archive for the 'C#' Category

Dependency Injection inside a loop vs via a factory – part 2

Saturday, February 6th, 2010

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’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’ve changed my test a bit so that Ninject uses a singleton as well.

Originally the Ninject kernel binding was like this:

NinjectContainer.Kernel.Bind<IAdditionProvider>().To<AdditionProvider>();

That tells Ninject to create a new instance of AdditionProvider every time. To get it to use the same instance – in effect a singleton – I changed the binding to this:

NinjectContainer.Kernel.Bind<IAdditionProvider>().ToConstant(new AdditionProvider());

I expected to see a huge performance gain, and feel like an idiot. There was a bit of a gain:

That’s roughly 8 seconds (or 12%) less then the 1m5s taken the first time around. So there’s a good gain to be had using ToConstant() to avoid creating unnecessary instances of the injected class, but still nothing like the benefits of only directly using Ninject outside of the loop.

Dependency Injection inside a loop vs via a factory

Saturday, February 6th, 2010

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’ve used the [Inject] 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’t see a problem with a dependency on what seems like a core component.

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.

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 – the new dependency on Ninject was failing. Then I read an article by Bob Martin and several of his tweets on the subject where he talks about the dependency framework itself becoming a dependency. Got that right.

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’t configured (to deal with the designer issues). It also lets me inject the dependency only once and reuse the result.

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:

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 < 1000; i++)
{
    for (int j = 0; j < 1000; j++)
    {
        var tester = NinjectContainer.Kernel.Get<InjectionTester>();
        tester.DoAdd(i, j);
    }
}

The second consumer of the test uses a factory to get the dependency:

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<IAdditionProvider>();
            }
            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 < 1000; i++)
{
    for (int j = 0; j < 1000; j++)
    {
        var tester = new FactoryTester();
        tester.DoAdd(i, j);
    }
}

The results are pretty impressive (looping a million times):

Thinking about it now it’s pretty obvious that DI is going to be a bit expensive, but seriously, using a factory is over 200 times faster. That should keep em quiet.

Injecting Rhino Mocks with Ninject

Wednesday, January 20th, 2010

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’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.

I’m using Ninject 2 for dependency injection, NUnit 2.5.3 for unit testing, and Rhino Mocks 3.6 for mocking. NUnit has a mocking framework built in but it doesn’t use strong typing, which I think was causing problems with Ninject.

What I’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.

Initially I’m using the default ConcreteFoo implementation of IFoo in the test. This test fails as intended:

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 "You don't want to see me"; } }
    }

    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<IFoo>().To<ConcreteFoo>();
        }

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

            Assert.That(fooConsumer.Foo.Name, Is.EqualTo("The foo for you"));
        }
    }
}

Settting up and binding the mock is all done in the test method. The mock IFoo 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 ConcreteFoo binding, this seems to be easier then setting up the kernel from scratch for the test (possibly I’m just missing how to rebind).

[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<IFoo>();
		Expect.Call(mockFoo.Name).Return("The foo for you");
		mocks.ReplayAll();

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

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

		Assert.That(fooConsumer.Foo.Name, Is.EqualTo("The foo for you"));
}

The test should now pass.

Declaring a class with inheritance and a generic type constraint in C#

Friday, November 13th, 2009

I’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’s not obvious how to write this. Any examples of type constraints I could find don’t have inheritance or interfaces as well. So, via a bit of trail and error, here is a right way to declare such a class:

public class MyClass<T> :
    BaseClass<T>, IMyInterface
    where T : ClassOfT
{...}

ZedGraph – .NET graph control

Friday, March 28th, 2008

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’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’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’s also a ZedGraphWeb control built in which is for use in ASP.NET apps (although I haven’t tried that out).

There are two concurrent versions for both .NET 1.1 and .NET 2 (which is very handy since I’m limited to .NET 1.1 at work). The only difference between the versions is apparently use of templates for collections.

There’s a CodeProject article that gives a pile of simple demo code, and the main site 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’s DLLs are dynamically linked they can be included in commercial software.

Logical XOR operator in C#

Tuesday, March 4th, 2008

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 && and || versus the bitwise operators (& and |). I guess it’s the same thing anyway, just a bitwise XOR operation on two booleans. Fascinating.

Could not find resources exception when modifying a form class in Visual Studio .NET 2003

Thursday, February 21st, 2008

I changed the name of a form class and added a new class at the top of the class file with the same name of the old form class, descending from the renamed class to avoid breaking old code. Then when I ran the app I got an exception saying that the form’s resources couldn’t be loaded. When I had a look at the resources file for the form (<project folder>\obj\Debug) a resources file was still being created for the old class name instead of the new one. Since this resources file is the one that gets linked into the DLL or exe, this meant that the new form class couldn’t find its resources. According to Microsoft KB318603 this is because other class definitions located before the form class definition will be picked up when naming the resources file. So if this happens, move the other class to after the form class (ie the MyForm.cs file should contain first the MyForm class then any other classes).

Of course the best thing would be to move the other classes into another file but that sounds like work :-)

Fine-tuning polymorphism in C# using the new keyword

Wednesday, August 8th, 2007

This doesn’t come up too often but can be useful. Sometimes, when using inheritance, it can be difficult to get the right implementation of a virtual method called. This is the kind of model I had today:

namespace InheritanceTest
{

	public class BaseClass
	{
		public BaseClass() {}

		public virtual void A(int count)
		{
			for (int i = 0; i < count; i++)
				B(string.Format("{0} Base Hello", i));	// This calls DerivedClass.B(string)
		}

		public virtual void B(string s)
		{
			Console.WriteLine("Base: "+s);
		}
	}

	public class DerivedClass : BaseClass
	{
		public DerivedClass() : base() {}

		public override void A(int count)
		{
			base.A(count);	// call BaseClass.A(int)
		}

		public override void B(string s)
		{
			Console.WriteLine("Derived: "+s);
		}
	}

	class MainClass
	{
		public static void Main(string[] args)
		{
			Console.WriteLine("Test begins:");

			DerivedClass obj = new DerivedClass();
			//obj.B(10);

			Console.WriteLine("Test ends.");
		}
	}
}

When this is compiled and run, the method called in BaseClass.A() is DerivedClass's implementation of B(). The series of method calls will look like this:

  1. DerivedClass.A()
  2. BaseClass.A()
  3. DerivedClass.B() ten times

So when BaseClass.A() makes the call to B(), the derived class's B() method is found and executed, rather than BaseClass.B(). This is exactly how you would usually want the inheritance to work; the derived class has methods that override the base class, and the base class calls fall through to the child's implementation of the virtual methods.

The problem with this is if you want to be able to use the base class's implementation of B() in BaseClass.A()'s call to B(). BaseClass.B()'s implementation may contain code required in BaseClass, but DerivedClass.B()'s implementation is not appropriate for use in BaseClass. Basically you want the following series of method calls:

  1. DerivedClass.A()
  2. BaseClass.A()
  3. BaseClass.B() ten times

We need to indicate to the compiler that, although DerivedClass.B() implements B(), it doesn't necessarily override BaseClass's implementation of B(). That is done by changing the override keyword in DerivedClass.B()'s declaration to new:

Change:

public override void B(string s)

to:

public new void B(string s)

The effect of this is that when B() is called in BaseClass, it will be BaseClass.B() that will be executed, because DerivedClass.B() is flagged as a new implementation of the B() method that does not override the existing one. The new DerivedClass.B() method is still visible in DerivedClass and beyond:

DerivedClass obj = new DerivedClass();
obj.B("Test");   // This will execute DerivedClass.B(), not BaseClass.B()

will execute DerivedClass.B().