Web API Controller的集成测试发出以下错误:类型“XXXController”没有默认构造函数

时间:2013-10-20 02:27:01

标签: asp.net-web-api ninject

完整的错误消息:

{
    "Message":"An error has occurred.",
    "ExceptionMessage":"Type 'XXXController' does not have a default constructor",
    "ExceptionType":"System.ArgumentException",
    "StackTrace":"   at System.Linq.Expressions.Expression.New(Type type)\r\n   at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n   at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}

我已经做了一些谷歌搜索,现在我仍然坚持下一步尝试。

我通过以下方式安装了NinjectDependencyResolver

PM> Install-Package Ninject.WebApi.DependencyResolver

我在TestInitialize方法中使用以下代码来创建HttpClient

 var kernel = new StandardKernel(/* ... */);

var config = new HttpSelfHostConfiguration(BaseAddress);

/* ... */

config.DependencyResolver = new NinjectDependencyResolver(kernel);

_client = new HttpClient(new HttpServer(config));

然后我在客户端发出PostAsync请求。结果的内容在顶部有错误。

提前致谢!

1 个答案:

答案 0 :(得分:0)

在输入此问题时,我仔细检查并注意到我没有将NinjectModule中的一个传入StandardKernel。添加注册传递给构造函数的类型的模块解决了该异常。如果我错过了某种类型的绑定,我希望能说出其他内容(例如“找不到IMyInterface的绑定”。)