Using Ninject with Asp.NET Web API Beta ApiController

前端 未结 5 517
没有蜡笔的小新
没有蜡笔的小新 2021-01-31 22:33

I\'m stuck. I was using the method outlined here for wcf web api p6 Ninject working with WCF Web API Preview 5, however things are quite a bit different with the mvc implementat

相关标签:
5条回答
  • 2021-01-31 22:57

    The same code will work for both MVC and the WebApi, however because the WebApi was inspired by MVC and the MVC assemblies do not have to be referenced in order to use WebApi (or vise versa), there is a fair amount of duplication of code between the two frameworks. If you want to use MVC you're dependencies will come from System.Web.Mvc, if you want to use WebApi you'll use System.Web.Http. If you want to use both you'll have to differentiate in your code which to use when, using a more explicit namespace resolution.

    In your case your problem is that MVC came first and the NinjectDependancyResolver class inherits from System.Web.Mvc.IDependencyResolver. You'll want to create an exact duplicate of the NinjectDependancyResolver class and instead inherit from System.Web.Http.IDependencyResolver instead. Use THIS class to setup your IoC and you'll be good to go.

    0 讨论(0)
  • 2021-01-31 23:00

    May sound silly but have you made sure you have a reference to the CommonServiceLocator / CommonServiceLocator.NinjectAdapter nuget package or associated assemblies. Your NinjectDependencyResolver may not be able to resolve the reference to IServiceLocator.

    0 讨论(0)
  • 2021-01-31 23:01

    I found the answer and updated my question above with the solution. The solution itself was more or less present in the Using the Web API Dependency Resolver article, i just had to keep tweaking for ninject. Both answers helped me quickly narrow this down so thanks to @Remo and @James.

    0 讨论(0)
  • 2021-01-31 23:02

    I never used the WebAPI but since the semantic of the IDependencyResolver is exactly the same as the one from MVC3 you should be able to use the same implementation: https://github.com/ninject/ninject.web.mvc/blob/master/mvc3/src/Ninject.Web.Mvc/NinjectDependencyResolver.cs

    Update: The Ninject.Web.WebAPi extension adds support for ApiControllers

    0 讨论(0)
  • I found a nice solution here.

    It's pretty easy if you're already using the Ninject CommonServiceLocator / Bootstrapper:

    private static IKernel CreateKernel() {
       var kernel = new StandardKernel();
       RegisterServices(kernel);
    
       GlobalConfiguration.Configuration.ServiceResolver
          .SetResolver(new NinjectServiceLocator(kernel));
       return kernel; 
    }
    
    0 讨论(0)
提交回复
热议问题