MVC5, Web API 2 and Ninject
Solution 1:
The Ninject.Web.WebApi NuGet package has just been released. From now on the preferred solution is using that package. I couldn't find any related documentation but after installing the package everything worked for me.
Install-Package Ninject.Web.WebApi
After installation both the normal MVC and the API controller instances are provided by Ninject.
If you have Ninject.Web.Common already installed make sure to save your bindings from NinjectWebCommon.cs and let Nuget rewrite NinjectWebCommon.cs during install and put back your bindings when finished.
As pointed out in the comments depending on your execution context you will need one of the following packages as well:
- Ninject.Web.WebApi.WebHost
- Ninject.Web.WebApi.OwinHost
- Ninject.Web.WebApi.Selfhost
The most common scenario is IIS for that pick the WebHost package.
In the case you start an IIS MVC5 web app from scratch and want to use Ninject install the following packages:
- Ninject - Ninject core dll
- Ninject.Web.Common - Common Web functionality for Ninject eg. InRequestScope()
- Ninject.MVC5 - MVC dependency injectors eg. to provide Controllers for MVC
- Ninject.Web.Common.WebHost - Registers the dependency injectors from Ninject.MVC5 when IIS starts the web app. If you are not using IIS you will need a different package, check above
- Ninject.Web.WebApi WebApi dependency injectors eg. to provide Controllers for WebApi
- Ninject.web.WebApi.WebHost - Registers the dependency injectors from Ninject.Web.WebApi when IIS starts the web app.
Solution 2:
You have this problem because Controller and ApiController use different Dependency Resolvers. Solution is very simple.
At first create new classes of Dependency Resolver and Dependency Scope. You can use this:
public class NinjectResolver : NinjectScope, IDependencyResolver
{
private readonly IKernel _kernel;
public NinjectResolver(IKernel kernel)
: base(kernel)
{
_kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectScope(_kernel.BeginBlock());
}
}
public class NinjectScope : IDependencyScope
{
protected IResolutionRoot resolutionRoot;
public NinjectScope(IResolutionRoot kernel)
{
resolutionRoot = kernel;
}
public object GetService(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).SingleOrDefault();
}
public IEnumerable<object> GetServices(Type serviceType)
{
IRequest request = resolutionRoot.CreateRequest(serviceType, null, new Parameter[0], true, true);
return resolutionRoot.Resolve(request).ToList();
}
public void Dispose()
{
IDisposable disposable = (IDisposable)resolutionRoot;
if (disposable != null) disposable.Dispose();
resolutionRoot = null;
}
}
After that, add next line to method CreateKernel() in NinjectWebCommon
GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);