<?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>blog.jorrit salverda.nl &#187; Inversion of Control</title>
	<atom:link href="http://blog.jorritsalverda.nl/tag/inversion-of-control/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.jorritsalverda.nl</link>
	<description></description>
	<lastBuildDate>Fri, 17 Dec 2010 18:08:54 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Maintainable MVC Series: Inversion of Control Container &#8211; StructureMap</title>
		<link>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/?utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=maintainable-mvc-series-inversion-of-control-container-structuremap</link>
		<comments>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/#comments</comments>
		<pubDate>Tue, 09 Feb 2010 21:22:23 +0000</pubDate>
		<dc:creator>Jorrit Salverda</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[Inversion of Control]]></category>
		<category><![CDATA[MVC]]></category>
		<category><![CDATA[StructureMap]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://blog.jorritsalverda.nl/?p=57</guid>
		<description><![CDATA[This article is part of the Maintainable MVC Series. To make your code testable the pattern to use is that of Dependency Injection. DI is nothing more than injecting all dependencies of a class instance through the constructor (or setters if you wish, but less intuitive when reading the code, and doesn&#8217;t guarantee all dependencies [...]]]></description>
			<content:encoded><![CDATA[<p><em>This article is part of the <a href="http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-introduction/">Maintainable MVC Series</a>.</em></p>
<p>To make your code testable the pattern to use is that of Dependency Injection. DI is nothing more than injecting all dependencies of a class instance through the constructor (or setters if you wish, but less intuitive when reading the code, and doesn&#8217;t guarantee all dependencies are set). For example if you have a controller that uses a factory and a repository you can both inject them into the constructor as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
public class Controller
{
	private readonly IFactory factory;
	private readonly IRepository repository;

	public Controller(IFactory factory, IRepository repository)
	{
		this.factory = factory;
		this.repository = repository;
	}
}
</pre>
<p><span id="more-57"></span></p>
<p>When looking at the constructor you immediately see on which components this class depends. Using interfaces makes testing even more simple, because then we can easily mock the dependencies. Creating an instance of the controller will look as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
IFactory factory = new Factory();
IRepository repository = new Repository();

Controller controller = new Controller(factory, repository);
</pre>
<p>Once your nesting of dependencies gets bigger, setting up your instances becomes quite cumbersome. This causes you to rethink before you add another dependency to a class. This hinders testability, so you would really want adding another dependency to be a piece of cake.</p>
<p>Enters Inversion Of Control container. The IOC container is some software that handles initialization of all your dependencies. StructureMap is on of the longest available ones for .Net. Others are Castle Windsor, Spring.NET, Unity, Ninject and others. What makes StructureMap very pleasant to work with is it&#8217;s extra facilities for testing.</p>
<p>First an example of how you use StructureMap to initialize your instances.</p>
<p>To setup which classes to use for which interfaces you do the following initialization once:</p>
<pre class="brush: csharp; title: ; notranslate">
ObjectFactory.Initialize(x =&gt;
	{
		x.For&lt;IFactory&gt;().Use&lt;Factory&gt;();
		x.For&lt;IRepository&gt;().Use&lt;Repository&gt;();
	});
</pre>
<p>Then every time you need an instance of your controller you can use the following code:</p>
<pre class="brush: csharp; title: ; notranslate">
Controller controller = ObjectFactory.GetInstance&lt;Controller&gt;();
</pre>
<p>StructureMap looks at the constructor of class Controller and sees it&#8217;s dependent on an IFactory and IRepository. It knows which concrete classes to use for these interfaces, so it creates those first and then creates the Controller instance by injecting them into the constructor.</p>
<h2>StructureMap in MVC</h2>
<p>In a standard MVC project your controllers are required to have a parameterless constructor, which is used to initialize them. Of course this is in conflict with the Dependency Injection we want to use the make our code testable and easy to setup with StructureMap. However MVC is extensible on this point, and we can provide our own ControllerFactory, which looks as follows:</p>
<pre class="brush: csharp; title: ; notranslate">
public class StructureMapControllerFactory : DefaultControllerFactory
{
	protected override IController GetControllerInstance(Type controllerType)
	{
		if (controllerType == null)
		{
			return base.GetControllerInstance(controllerType);
		}

		try
		{
			return ObjectFactory.GetInstance(controllerType) as Controller;
		}
		catch (StructureMapException exception)
		{
			// log an error with the exception and ObjectFactory.WhatDoIHave()
			throw;
		}
	}
}
</pre>
<p>In <strong>MVC 2</strong> the signature of method <em>GetControllerInstance</em> looks a little different, so our StructureMapControllerFactory will be adjusted correspondingly:</p>
<pre class="brush: csharp; highlight: [3,4,8]; title: ; notranslate">
public class StructureMapControllerFactory : DefaultControllerFactory
{
	protected override IController GetControllerInstance(RequestContext requestContext,
														 Type controllerType)
	{
		if (controllerType == null)
		{
			return base.GetControllerInstance(requestContext, controllerType);
		}

		try
		{
			return ObjectFactory.GetInstance(controllerType) as Controller;
		}
		catch (StructureMapException exception)
		{
			// log an error with the exception and ObjectFactory.WhatDoIHave()
			throw;
		}
	}
}
</pre>
<p>This factory makes sure that StructureMap initializes your controllers. Now to make MVC use this factory we add the following code to the Global.asax.cs:</p>
<pre class="brush: csharp; title: ; notranslate">
protected void Application_Start()
{
	// initialize structuremap container
	StructureMapBootstrapper.Bootstrap();

	// let structuremap handle creating controllers
	ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
</pre>
<p>On the last line we set the factory. The first line calls the bootstrapper, which does the initialization of StructureMap.</p>
<pre class="brush: csharp; highlight: [9,10,11,12,13,14,15,16]; title: ; notranslate">
public class StructureMapBootstrapper : IBootstrapper
{
	private static bool hasStarted;

	public void BootstrapStructureMap()
	{
		ObjectFactory.Initialize(x =&gt;
		{
			x.For&lt;ISessionHandler&gt;().Use&lt;SessionHandler&gt;();
			x.For&lt;ITempDataHandler&gt;().Use&lt;TempDataHandler&gt;();

			x.ForSingletonOf&lt;ICacheHandler&gt;().Use&lt;CacheHandler&gt;();

			x.AddRegistry&lt;FactoryRegistry&gt;();
			x.AddRegistry&lt;RepositoryRegistry&gt;();
			x.AddRegistry&lt;ServiceRegistry&gt;();
		});
	}

	public static void Restart()
	{
		if (hasStarted)
		{
			ObjectFactory.ResetDefaults();
		}
		else
		{
			Bootstrap();
			hasStarted = true;
		}
	}

	public static void Bootstrap()
	{
		new StructureMapBootstrapper().BootstrapStructureMap();
	}
}
</pre>
<p>The highlighted <em>ObjectFactory.Initialize</em> part in the code above is the part that is custom for your project. Here you specify which concrete class to use for which interface. The initialization isn&#8217;t very fast, but only performed once in production code. For testing purposes this is to costly, so the restart action is provided.</p>
<p>You can also see the lines with AddRegistry: the registries that are added are a way to group your code, because otherwise the bootstrapper can become quite long. A definition of a registry:</p>
<pre class="brush: csharp; title: ; notranslate">
public class FactoryRegistry : Registry
{
	public FactoryRegistry()
	{
		For&lt;IInputModelFactory&gt;().Use&lt;InputModelFactory&gt;();
		For&lt;IViewModelFactory&gt;().Use&lt;ViewModelFactory&gt;();
	}
}
</pre>
<p>The specific StructureMap code in your project only consists of the BootStrapper, the registries and the ControllerFactory. It&#8217;s best to try and avoid the use of ObjectFactory.GetInstance throughout your code as much as possible. It makes it harder to replace StructureMap if you want to, but more importantly it makes your code harder to test. One case where you&#8217;ll probably won&#8217;t manage without is in the case of attributes. The creation of attribute instances is done by MVC and needs a parameterless constructor as well. However we can&#8217;t replace the factory in this case.</p>
<p>Unfortunately we need an extra use of ObjectFactory.GetInstance, but we can do it within the constructor to keep it testable:</p>
<pre class="brush: csharp; title: ; notranslate">
public class CustomAttribute : ActionFilterAttribute
{
	private readonly ISessionHandler sessionHandler;

	public CustomAttribute()
	: this(ObjectFactory.GetInstance&lt;ISessionHandler&gt;())
	{
	}

	public CustomAttribute(ISessionHandler sessionHandler)
	{
		this.sessionHandler = sessionHandler;
	}
</pre>
<p>If a class is created by StructureMap it defaults to the constructor with the most parameters.</p>
<h2>Testing with AutoMocker</h2>
<p>Okay, on to the reason I prefer StructureMap as an IOC container: AutoMocker. The RhinoAutoMocker creates an instance of the class under test and creates a Rhino Mock object for all (interfaced) dependencies. No more creation of mock objects yourself. And even more important you can add another dependency to a class without having to fix all tests that create an instance.</p>
<p>A test fixture will look as follows:</p>
<pre class="brush: csharp; highlight: [21,27]; title: ; notranslate">
[TestFixture]
public class AdvertsControllerTests
{
	private RhinoAutoMocker&lt;Controller&gt; autoMocker;
	private Controller controller;

	[SetUp]
	public void Setup()
	{
		StructureMapBootstrapper.Restart();

		autoMocker = new RhinoAutoMocker&lt;Controller&gt;(MockMode.AAA);
		controller = autoMocker.ClassUnderTest;
	}

	[Test]
	public void CreatePostShouldCallFormHandlerForValidPost()
	{
		//Arrange
		FormEditModel editModel = new FormEditModel();
		autoMocker.Get&lt;IFormHandler&gt;().Expect(p =&gt; p.CreatePost(Arg&lt;FormEditModel&gt;.Is.Anything)).Return(true);

		//Act
		controller.CreatePost(editModel);

		//Assert
		autoMocker.Get&lt;IFormHandler&gt;().VerifyAllExpectations();
	}
</pre>
<p>The highlighted <em>autoMocker.Get&lt;IFormHandler&gt;()</em> lines retrieve a mock object and set expectations. So, per test you only have to set the dependencies neccessary for the code under test. A controller often has a lot of dependencies, but they&#8217;re not used by every action.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.jorritsalverda.nl/2010/02/09/maintainable-mvc-series-inversion-of-control-container-structuremap/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
	</channel>
</rss>

