I have the following packages and their dependencies installed in my WebAPI project:
Ninject.Web.WebApi
Ninject.Web.WebApi.OwinHost
I've got a situation where I have a service, and into it injected other services. One of these injected services had another injected services, and one of them was not registered properly for dependency injection.
I set a breakpoint in the constructor of services that were injected in controller (services before one that was causing a problem). In debugging it was shown for which service it cannot resolve the dependency.
What worked for me was adding the NuGet package Ninject.Web.WebApi.WebHost
as described here: https://github.com/ninject/Ninject.Web.WebApi/wiki/Setting-up-an-mvc-webapi-application
I too was trying to make an 'only API' app, but faced similar issues. For me personally, in the end it came down the selecting the right starting template.
Despite going for API-only, when in the 'Create a new ASP.NET Web Application" wizard, selecting the 'Empty' application-type and choosing MVC and Web API in the 'add folders & core references' section made Ninject work fine:
As opposed to the 'Web API' application, which didn't play nice with Ninject:
After that, it's simply to add the Ninject.Web.WebApi.WebHost package, which adds the NinjectWebCommon.cs class, and start adding dependencies.
This applies to older versions of Ninject, or if you are not using the auto-generated bootstrap code from Ninject.Web.WebApi.Webhost
.
You are missing a dependency resolver, its a really basic implementation:
public class NinjectHttpDependencyResolver : IDependencyResolver, IDependencyScope
{
private readonly IKernel _kernel;
public NinjectHttpDependencyResolver(IKernel kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return this;
}
public void Dispose()
{
//Do nothing
}
public object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.GetAll(serviceType);
}
}
Then just register it when you create the kernel:
var httpResolver = new NinjectHttpDependencyResolver(kernel);
GlobalConfiguration.Configuration.DependencyResolver = httpResolver;
My solution is add "public" keyword to constructor.
Did you modify your OWIN Startup
class to call app.UseNinjectWebApi
and app.UseNinjectMiddleware
rather than calling app.UseWebApi
?
Startup.cs in the Ninject Web API samples does this...