设置ASP.NET MVC ControllerFactory无效

时间:2011-02-10 00:36:44

标签: asp.net-mvc inversion-of-control structuremap

我正在尝试使用StructureMap构建我的ASP.NET MVC2控制器,但ASP.NET似乎并不记得我在Global.asax文件中调用了ControllerBuilder.Current.SetControllerFactory

具体来说,我得到的错误是我的控制器没有无参数构造函数。堆栈跟踪显示我的自定义ControllerFactory从未实际执行过。

这是我对该方法的调用,该方法应该告诉ASP.NET使用哪个ControllerFactory:

Sub Application_Start()

    RegisterRoutes(RouteTable.Routes)

    ControllerBuilder.Current.SetControllerFactory(GetType(StructureMapControllerFactory))

    BootStrapper.RegisterDependencies()

End Sub

这是我收到的例外情况。

[TargetInvocationException: Exception has been thrown by the target of an invocation.]
  System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
  System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
  System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
  System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
  System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80

为什么ASP.NET忘记使用哪个ControllerFactory?

2 个答案:

答案 0 :(得分:2)

您的StructureMapControllerFactory是如何定义的?它有默认构造函数吗?

如果没有,请尝试使用SetControllerFactory方法的第二次重载:

// First create the controllerFactory instance...

ControllerBuilder.Current.SetControllerFactory(controllerFactory);

答案 1 :(得分:0)

您必须在RegisterRoutes ...

之前设置您的controllerFactory