Ninject error in WebAPI 2.1 - Make sure that the controller has a parameterless public constructor

后端 未结 10 2144
心在旅途
心在旅途 2020-12-31 00:39

I have the following packages and their dependencies installed in my WebAPI project:

Ninject.Web.WebApi Ninject.Web.WebApi.OwinHost

10条回答
  •  被撕碎了的回忆
    2020-12-31 00:53

    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 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;
    

    提交回复
    热议问题