I recently tried to implement dependency injection using StructureMap. I managed to follow the example all the way but I'm encountering a thrown exception every time I try to run the application. Here's some code snippets from my controller factory.
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(Type controllerType)
{
if (controllerType == null)
throw new ArgumentNullException("controllerType");
return ObjectFactory.GetInstance(controllerType) as Controller;
}
}
My Global.asax calls a static BootStrapper class which registers all my dependencies but it looks like the StructureMapControllerFactory's GetControllerInstance is getting called twice. The first time it's called, a proper controllerType is passed in but it's always null on the second calling.
The first time GetControllerInstance is called, the type is set to HomeController which is correct. The code the fires in HomeController and it returns the View(). On the return of the View(), the Page_Load event is called on the aspx file. After stepping through that, it arrives at a line:
httpHandler.ProcessRequest(HttpContext.Current);
That's where the GetControllerInstance is called the second time.
Here's my Global.asax bits which may be relevant:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
Bootstrapper.ConfigureStructureMap();
ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory());
}
I'm very keen to get dependency injection working and would be most appreciative if anyone can help me out. :)