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.

Community
  • 1
  • 1
Tim
  • 377
  • 7
  • 19
  • 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) – Tim Feb 11 '14 at 20:12
  • Related: https://stackoverflow.com/questions/15908019/simple-injector-unable-to-inject-dependencies-in-web-api-controllers – Steven Feb 11 '14 at 21:11
  • In modern version Ninject Web API has own DependencyResolver [http://stackoverflow.com/a/31137065/1295211][1] [1]: http://stackoverflow.com/a/31137065/1295211 – user1295211 Jun 30 '15 at 11:36
  • In modern version Ninject Web API has own DependencyResolver [http://stackoverflow.com/a/31137065/1295211][1] [1]: http://stackoverflow.com/a/31137065/1295211 – user1295211 Jun 30 '15 at 11:38

1 Answers1

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
harriyott
  • 10,505
  • 10
  • 64
  • 103
Tim
  • 377
  • 7
  • 19