5

将 Ninject 与 Web API 一起使用时出现此错误,但它适用于 MVC 控制器:

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>();
        }
    }

全球.asax.cs:

BundleConfig.RegisterBundles(BundleTable.Bundles);

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

产品控制器:

   public class ProductController : ApiController
        {
            private IProductRepository repository;

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

            public IEnumerable<Product> GetAllProducts()
            {
                return repository.Products.AsEnumerable();
            }
        }
4

3 回答 3

3

您已经覆盖了DefaultControllerFactory. 但这用于实例化 ASP.NET MVC 控制器(一个派生自System.Web.Mvc.Controller)。它与 ASP.NET Web API 控制器(从System.Web.Http.ApiController.

所以基本上你在这里所做的是依赖注入到 ASP.NET MVC。如果您想将其用于 Web API,您可以查看以下指南:

于 2013-07-20T09:54:37.347 回答
2

您应该使用最新的 Ninject Web API 包,它已经解决了这些问题。见这里: http: //nuget.org/packages/Ninject.Web.WebApi.WebHost/

于 2013-07-20T11:36:31.707 回答
1

您需要设置DependencyResolver. HttpConfiguration您所做的是针对 ASP.NET MVC 而不是 ASP.NET Web API。

所以获取 NuGet 包并设置 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
于 2013-07-20T14:05:38.910 回答