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

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

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.

Using Jeditable for inline editing

February 4th, 2010

Using the Jeditable plugin for jQuery enables inline editing of a block of text. This makes it easy to take a static view and simply drop in editability. Say we start with the following HTML:

<label>Name:</label> <span class="employeeName">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating">Highly awesome</span>

We want to be able to edit the employeeName and employeeRating spans. We need two actions (asssuming an MVC framework) to update the name and rating. The URLs might be something like /employee/set_name/{id} and /employee/set_rating/{id}. Each action should accept HTTP POST, take the new value in $_REQUEST['new_value'] or similar, and return a HTTP status of 200 on success and 500 on failure, with the error message in the response. For example, using Slab (my PHP5 MVC framework, in development) the set_name action might be like this:

class EmployeeController extends AppController {
	function set_name($id) {
		$this->Employee->save(array(
			'id' => $id',
			'name' => $this->data['new_value']);
		));
		return $this->ajaxSuccess($this->data['new_value']);
	}
}

Slab catches uncaught exceptions and returns an AJAX failure with the exception message as the body of the response.

To hook up the fields to the actions, modify the HTML to include the URLs to the actions. While this means the markup has behavioural elements and isn’t purely presentational (and has a non-standard attribute), it makes the script a bit simpler and easy to move into a static .js file, and is a quick way to get a page working.

<label>Name:</label> <span class="employeeName" editUrl="/employee/set_name/7">Ben Scott</span><br/>
<label>Rating:</label> <span class="employeeRating" editUrl="/employee/set_rating/7">Highly awesome</span>

Now for the script itself:

$(function(){
	$('.employeeName, .employeeRating').editable(
		function(value, settings) {
			return $.ajax({
				url: $(this).attr('editUrl'),
				data: { 'new_value': value },
				async: false,
				type: 'post'
			}).responseText;
		}, {
			indicator: 'Saving...',
			tooltip: 'Click to edit',
			onblur: 'submit'
		}
	);
});

The first argument is a function that returns the new value of the field. This is important when doing things like replacing line breaks with <br/> which we’re not worrying about, but it also gives us the ability to write our own AJAX code. By default Jeditable makes assumptions about how the update is done. The async option in the call to $.ajax() blocks until the call returns, and lets the function return the response of the AJAX call. The second argument are options to set some text to show while calling the update function, the tooltip to display when hovering over the span, and to submit changes on blurring the input which makes it seem a bit more usable when there are multiple fields.

Injecting Rhino Mocks with Ninject

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.

Cliche – an extremely simple view template engine for jQuery

December 21st, 2009

I’ve written a very simple plugin for jQuery that takes a template and a model and returns a view of the model. To make sure it worked I wrote some tests and examples, and since I did that I figured I would write a little mini-site. The plugin itself is pretty straightforward:

(function($){
	$.fn.cliche = function(model){
		var template = $(this).html();
		template = template.replace(/%7C/g, '|');	// pipes in a href like <a href="|... get converted to %7C, convert it back
		template = template.replace(/\|.*?\|/g, function(f) {
			var val = model;
			var fieldParts = f.replace(/\|/g, '').split('.');
			for (var i = 0; i < fieldParts.length; i ++) {
				val = val[fieldParts[i]];
			}
			return val;
		});
		return template;
	};
}(jQuery));

It is used by setting up a template (putting it into a script type="text/html" block is convenient and hides it from display) and calling cliche(model) on the jQuery object:

<div id="output">
	<ul></ul>
</div>
<script type="text/html" id="testTemplate">
	<li id="item|id|"><a href="viewItem?id=|id|">|name|</a></li>
</script>
<script type="text/javascript">
	$('#output ul').append(
		$('#testTemplate').cliche({
			id: 1, name: 'Lorem'
		})
	);
</script>

Cliche is licensed under a Creative Commons Attribution 2.5 Australia license. Check it out at http://cliche.belfryimages.com.au.

RegEx Sandbox

December 15th, 2009

I’ve just made a new tool live, it is a sandbox for playing with simple regular expressions in Javascript. I’ve used a couple of other web-based regex tools, what makes this one different is the result of the regular expression is shown live (as well as a couple of examples of what the regex should look like in code). Try out the RegEx Sandbox at regex.belfryimages.com.au.

Form validation with jQuery

December 9th, 2009

Every time I’ve implemented client-side form validation I’ve started from scratch and done it a little differently. Usually it devolves into a messy set of if statements and duplicated code. Here’s my latest method, which separates the validation rules from the processing. It uses jQuery because if you’re not using a Javascript library you should be. This will only handle relatively simple validation cases.

So start with a form:

	<form id="mailingListSubscription" action="subscribe.php">
		Name: <input type="text" name="name" id="name" /><br />
		Email: <input type="text" name="email" id="email" /><br />
		Phone: <input type="text" name="phone" id="phone" /><br />
		<button type="submit">Subscribe</button>
	</form>

All fields are required, and I’m going to use some magical regex (found on the interthingy somewhere) to validate the email address. This script sets up the rules:

	var rules = [
		{ id: 'name', test: function(val) { return val != ''; }, msg: 'Please enter your name' },
		{ id: 'email', test: function(val) { return val.search(/^[^@]+@[^@]+.[a-z]{2,}$/i) != -1; }, msg: 'Please enter a valid email address' },
		{ id: 'phone', test: function(val) { return val != ''; }, msg: 'Please enter your phone number' }
	];

Each rule has the id of the form element being tested, a message that gets displayed on failing the rule, and a function that validates the value of the form element. I also could add multiple rules for the one input.

This script sets up the submit handler for the form, which does the validation using the array of rules set up above:

	$(function(){
		$('form#mailingListSubscription').submit(function(){
			for (var i = 0; i < rules.length; i ++) {
				var rule = rules[i];
				var target = $('#'+rule.id);
				if (!rule.test(target.val())) {
					alert(rule.msg);
					target.focus();
					return false;
				}
			}
			return true;
		});
	});

On a test failing, the rule’s msg value is shown and the target of the test gets focus. This could be changed to something more user friendly like showing the message next to the target field.

Deleting items in a table with AJAX via JQuery

November 29th, 2009

This is a very straight-forward tutorial on implementing a jQuery-driven ‘delete via AJAX’ feature. Say we have a plain HTML table containing a list of items and a ‘Remove’ link. I’m not going to describe the back-end, but I’m assuming something groovy like CakePHP or ASP.NET MVC. I’ve also assumed that the delete request always succeeds and never returns an error, which may not be the case. The script itself is a more than required but is my preferred method as I can extend the elements in the UI fairly easily.

	<table>
		<tr><td>Chickpeas</td>      <td><a href="/items/delete/1" class="delete">Delete</a></td></tr>
		<tr><td>Garlic</td>         <td><a href="/items/delete/2" class="delete">Delete</a></td></tr>
		<tr><td>Olive oil</td>      <td><a href="/items/delete/3" class="delete">Delete</a></td></tr>
		<tr><td>Tahini</td>         <td><a href="/items/delete/4" class="delete">Delete</a></td></tr>
		<tr><td>Cumin</td>          <td><a href="/items/delete/5" class="delete">Delete</a></td></tr>
		<tr><td>Lemon juice</td>    <td><a href="/items/delete/6" class="delete">Delete</a></td></tr>
	</table>

The delete hrefs (/items/delete/XX) link to an action or page that deletes the specified item and returns a HTTP status of 200 (OK). If the action just redirected to the current page then this table should work as it stands, which is probably a good way to check that everthing works as expected without involving AJAX features. If you just want to set up the client side without implementing any server-side code, create the following in delete_test.php and use it for the delete links:

<?php header('HTTP/1.1 200 OK'); ?>

Make sure that jQuery 1.3+ has been included in the page and add the following:

<script type="text/javascript">
$(function(){
	var ui = {
		init: function(){
			$('a.delete').live('click', ui.delete_click);
		},

		delete_click: function(){
			link = this;
			$.get(link.href, function(data, status) {
				$(link).parents('tr').remove();
			});
			return false;
		}
	};

	ui.init();
});
</script>

Very basic stuff but it works. It could be jazzed up by fading out the items first or updating a status label. If there is a significant delay between calling the delete action and getting a response the user may not think anything has happened, so perhaps the delete link should change or be disabled.

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

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
{...}

New tool list

November 7th, 2009

I’ve added my tool list to the sidebar. This is a collection of free tools and software that I absolutely have to have on all my computers (there’s a few of them).