2013-07-20 3 views
4

에 대해이 오류를 얻었으나, 그것은 MVC 컨트롤러와 함께 작동 :Ninject에 Asp.net 웹 API

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

답변

2

DefaultControllerFactory을 재정의했습니다. 그러나 이것은 ASP.NET MVC 컨트롤러 (System.Web.Mvc.Controller에서 파생 된 컨트롤러)를 인스턴스화하는 데 사용됩니다. ASP.NET 웹 API 컨트롤러 (System.Web.Http.ApiController에서 파생 된 컨트롤러)와는 아무런 관련이 없습니다.

기본적으로 여기서 한 것은 ASP.NET MVC에 대한 종속성 주입입니다. 당신이 웹 API에 대해이 작업을 사용하려면 다음과 같은 가이드를 한 번 봐 걸릴 수 있습니다 :

1

HttpConfiguration의 속성을 DependencyResolver으로 설정해야합니다. ASP.NET MVC 및 ASP.NET 웹 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