MVC5, WebAPI2 and Ninject Parameterless constructor error
Asked Answered
R

1

4

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.

Raquel answered 11/2, 2014 at 20:10 Comment(4)
P.S GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel); seems to be unnecessary for ApiControllers (they work without it) and adding it doesn't fix MVC Controller's. (I assume this is because I am using Ninject.Web.WebAPI instead of Ninject.MVC3)Raquel
Related: #15908519Landel
In modern version Ninject Web API has own DependencyResolver [https://mcmap.net/q/273206/-mvc5-web-api-2-and-ninject][1] [1]: https://mcmap.net/q/273206/-mvc5-web-api-2-and-ninjectPurine
In modern version Ninject Web API has own DependencyResolver [https://mcmap.net/q/273206/-mvc5-web-api-2-and-ninject][1] [1]: https://mcmap.net/q/273206/-mvc5-web-api-2-and-ninjectPurine
R
4

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
Raquel answered 7/3, 2014 at 16:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.