I created a custom controller factory to be able to inject service instances to my controllers using StructureMap.
Everything works fine with the exception that with every request the controller factory is called a first time in which it resolves the controller properly and a second time in which the controllerType parameter is null and so StructureMap’s GetInstance method throws an ArgumentNullException: Value cannot be null. Parameter name: key.
The application actually does not crash but if I’m debugging it always stops there and I have to manually continue the execution so the view gets displayed.
Could anyone please explain why this is happening and how could I solve it.
Here is the code from both my Global.asax and the controller factory:
Controller Factory:
public class IocControllerFactory : DefaultControllerFactory
{
private readonly IContainer container;
public IocControllerFactory(IContainer container)
{
if(container == null) throw new ArgumentNullException("container");
this.container = container;
}
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return this.container.GetInstance(controllerType) as IController;
}
}
Global.asax
private void RegisterControllerFactory()
{
var ioc = new Container();
var controllerFactory = new IocControllerFactory(ioc);
ControllerBuilder.Current.SetControllerFactory(controllerFactory);
ioc.Configure(r =>
r.Scan(x =>
{
x.AssemblyContainingType<UserAccountController>();
x.AddAllTypesOf<IController>();
x.Include(t => typeof(IController).IsAssignableFrom(t));
}
));
ioc.Configure(r => r
.For<IUserAccountService>()
.Use<UserAccountService>());
}
Thank you so much for any help.
Remember that ASP.NET MVC punches every request that does not map to a file through the controller factory with the default configurations. And most browsers request a favicon.ico file by default. So, what is happening is your favicon is getting called but that don’t map to a type so StructureMap is getting a null type and erroring out.
Easiest fixes are to add a favicon.ico file or to add an ignore for the route.