Ninject for Asp.net Web API

Alv*_*vin 5 ninject ninject.web.mvc asp.net-mvc-4 asp.net-web-api

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

Type 'App.Web.Controllers.ProductController' does not have a default constructor
Run Code Online (Sandbox Code Playgroud)

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>();
        }
    }
Run Code Online (Sandbox Code Playgroud)

Global.asax.cs:

BundleConfig.RegisterBundles(BundleTable.Bundles);

            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory());
Run Code Online (Sandbox Code Playgroud)

ProductController:

   public class ProductController : ApiController
        {
            private IProductRepository repository;

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

            public IEnumerable<Product> GetAllProducts()
            {
                return repository.Products.AsEnumerable();
            }
        }
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 3

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

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