MVC5, WebAPI2 and Ninject Parameterless constructor error

*爱你&永不变心* 提交于 2019-12-18 08:55:51

问题


So I have the exact opposite problem as MVC5, Web API 2 and Ninject

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

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.


回答1:


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.

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)); 

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

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


来源:https://stackoverflow.com/questions/21711996/mvc5-webapi2-and-ninject-parameterless-constructor-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!