Question

I got this error when using Ninject with Web API, but it works with MVC Controller:

Type 'App.Web.Controllers.ProductController' does not have a default constructor

NinjectControllerFactory :

public class NinjectControllerFactory : DefaultControllerFactory
    {
        private IKernel ninjectKernel;

        public NinjectControllerFactory()
        {
            ninjectKernel = new StandardKernel();
            AddBindings();
        }

        protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
        {
            return controllerType == null ? null : (IController)ninjectKernel.Get(controllerType);
        }

        public void AddBindings()
        {
            ninjectKernel.Bind<IProductRepository>().To<EFProductRepository>();
        }
    }

Global.asax.cs :

BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());

ProductController :

   public class ProductController : ApiController
        {
            private IProductRepository repository;

            public ProductController(IProductRepository ProducteRepository)
            {
                this.repository = ProductRepository;
            }

            public IEnumerable<Product> GetAllProducts()
            {
                return repository.Products.AsEnumerable();
            }
        }
Was it helpful?

Solution

You have overriden the DefaultControllerFactory. But this is used to instantiate ASP.NET MVC controllers (one deriving from System.Web.Mvc.Controller). It has strictly nothing to do with ASP.NET Web API controllers (the ones deriving from System.Web.Http.ApiController).

So basically what you have done here is dependency injection into ASP.NET MVC. If you want to use this for the Web API you may take a look at the following guides:

OTHER TIPS

You should use the latest Ninject Web API package, which solves these problems already. See here: http://nuget.org/packages/Ninject.Web.WebApi.WebHost/

You need to set DependencyResolver property of the HttpConfiguration. What you have done was for ASP.NET MVC and not ASP.NET Web API.

So get the NuGet package and set DependencyResolver:

var kernel = new StandardKernel();
// use kernel to register your dependencies
var dependencyResolver = new NInjectResolver(kernel);
config.DependencyResolver = dependencyResolver; // config is an instance of HttpConfiguration based on your hosting scenario
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top