Structuremap and base controller in MVC4: Value cannot be null

531 Views Asked by At

I'm using Structuremap for DI, setting it up with a bootstrapper:

public class Bootstrapper {
    public static void ConfigureDependencies() {
        ObjectFactory.Initialize(x => x.AddRegistry<ControllerRegistry>());
    }
    public class ControllerRegistry : Registry {
        public ControllerRegistry(){
            For<IService1>().Use<Service1>();
            For<IService2>().Use<Service2>();
            For<IService3>().Use<Service3>();
        }
    }
}

In the file "EngineFactory.cs" I have this:

public class EngineFactory : DefaultControllerFactory {
    protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType) {
        return ObjectFactory.GetInstance(controllerType) as IController;
    }
}

I have two controllers with the appropiate views:

Login/Index:

This is a simple page where people can login. Nothing fancy and the DI is working perfect. As soon as someone has logged in, he/she is redirected to Home/Index:

Home/Index:

This is where the problem occurs. The controller has a base controller, looking something like this:

public class HomeController : MyBaseController{
    public HomeController(IService1 myService) : base(myService){
        // Do something cool
    }

The code for MyBaseController:

public class MyBaseController: Controller {
    public MyBaseController(IService1 myService){
        // Do something cools... Please?
    }
}

This gives errors on the home-controller: Value cannot be null. Parameter name: key

When I remove the base controller from the home-controller (and make it build again), it works fine.

I searched Google and stackoverflow and this is what I tried, but did not work:

1:

try {
    return (controllerType == null)
        ? base.GetControllerInstance(requestContext, controllerType)
        : ObjectFactory.GetInstance(controllerType) as IController;
} catch (Exception ex) {
        return null;
}

Gives error: The IControllerFactory 'My.Application.App_Start.EngineFactory' did not return a controller for the name 'Home'.

2:

routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });

No effect

3:

if (controllerType == null)
    return base.GetControllerInstance(requestContext, controllerType);
var controller = ObjectFactory.GetInstance(controllerType);
return (IController)controller;

Other error: Source cannot be found /Home

Does anyone know how to fix this?

Thanks in advance

0

There are 0 best solutions below