值不能为空。参数名称:key
自从我将 StructureMapControllerFactory 实现为我的 DefaultControllerFactory 以来,我已经开始收到此错误。
实际上我从 MVC Sample App StoreFront 复制了代码,但我不明白为什么这个错误不断弹出。即使出现此错误,应用程序仍然运行。
这个错误的原因可能是什么?
谢谢你的时间
System.ArgumentNullException was unhandled by user code
Message="Value cannot be null.\r\nParameter name: key"
Source="mscorlib"
ParamName="key"
StackTrace:
at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.ContainsKey(TKey key)
at StructureMap.Util.Cache`2.get_Item(KEY key)
at StructureMap.BuildSession.CreateInstance(Type pluginType)
at StructureMap.Container.GetInstance(Type pluginType)
at StructureMap.ObjectFactory.GetInstance(Type pluginType)
at Yacht.Web.Controllers.StructureMapControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) in D:\Documents\WebSites\JOBS\Yacht\Yacht.Web\Controllers\StructureMapControllerFactory.cs:line 16
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
InnerException:
Run Code Online (Sandbox Code Playgroud)
这是 StructureMapControllerFactory 类
public class StructureMapControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(System.Web.Routing.RequestContext requestContext, Type controllerType)
{
return ObjectFactory.GetInstance(controllerType) as Controller;
}
}
Run Code Online (Sandbox Code Playgroud)
另请注意,如果模型定义的属性未映射到数据库字段,则可能会发生此错误。追踪这个问题有点麻烦,所以我会留下一个答案,以防其他人遇到同样的问题。
我的修复很简单,包括 DataAnnotations:
using System.ComponentModel.DataAnnotations;
Run Code Online (Sandbox Code Playgroud)
然后在特定属性上使用 NotMapped 注解:
[NotMapped]
public string SomeCustomProperty { get; set; }
Run Code Online (Sandbox Code Playgroud)