MVC5、WebAPI2 和 Ninject 无参数构造函数错误 [英] MVC5, WebAPI2 and Ninject Parameterless constructor error

查看:29
本文介绍了MVC5、WebAPI2 和 Ninject 无参数构造函数错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我遇到了与 MVC5、Web API 2 和 Ninject 完全相反的问题

我有一个新的 MVC5/WebAPI2 项目,它同时包含Controller"和ApiControllers".

I have a new MVC5/WebAPI2 project, that has both "Controller"s and "ApiControllers".

我使用的是 Ninject.Web.WebAPI 的最新不稳定版本,对 NinjectDependencyResolve.cs 和 Ninject.WebCommom.cs 没有任何代码更改(除了绑定我的依赖项)ApiController 的构造函数注入有效.但是,当我调用 MVC 控制器时,我得到:

I'm using the latest unstable version of Ninject.Web.WebAPI with no code changes to NinjectDependencyResolve.cs and Ninject.WebCommom.cs (besides binding my dependency) the ApiController's constructor injection works. However, when I call a MVC Controller I get:

没有为此对象定义无参数构造函数.

No parameterless constructor defined for this object.

推荐答案

问题是您需要一个用于 MVC 和 WebAPI 的依赖关系解析器.根据您使用的 Ninject 库集,您只能获得其中一个.

The issue is you need a Dependency Resolver for both MVC and WebAPI. Depending on which set of Ninject libraries you use, you only get one of those wired in for you.

即如果您使用 Ninject.Web.WebAPI 库,您将需要手动设置 MVC 解析器:

i.e. if you use the Ninject.Web.WebAPI library you will need to manually set the MVC resolver:

System.Web.Mvc.DependencyResolver.SetResolver(new NinjectResolver(kernel)); 

(我在 NinjectWebCommon.cs CreateKernel() 中做了这个)

(I did this in NinjectWebCommon.cs CreateKernel())

您的 Ninject 解析器可以继承 WebAPI 和 MVC 的接口:

Your Ninject resolver can inherit the interface for both WebAPI and MVC:

public class NinjectResolver : NinjectScope, 
    System.Web.Http.Dependencies.IDependencyResolver, 
    System.Web.Mvc.IDependencyResolver

这篇关于MVC5、WebAPI2 和 Ninject 无参数构造函数错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆