将Ninject与Asp.NET Web API Beta ApiController一起使用

时间:2012-02-23 16:44:49

标签: asp.net-mvc ninject asp.net-web-api

我被困住了。我使用的是wcf web api p6 Ninject working with WCF Web API Preview 5中概述的方法,但是测试版中的mvc实现情况有所不同。这里有一篇很好的文章http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver,讨论构建自己的自定义依赖项解析器,但是我想使用我用于mvc视图控制器的相同实现...例如。 Ninject。我在文章中也尝试了一些基于IoC Unity示例的内容,但还没有任何内容。任何帮助我指向正确方向的人都会非常感激。我也会继续自己挖掘。提前谢谢!

这是我在的地方。我正在使用WebActivator来引导代码,但我已经把它放到了Application_Start()中,只是为了更多的东西。

    protected void Application_Start()
    {
        var kernel = new StandardKernel(new MyNinjectModule());
        GlobalConfiguration.Configuration.ServiceResolver.SetResolver(new NinjectDependencyResolver(kernel));
    }

我收到以下错误:
类型Ninject.Web.Mvc.NinjectDependencyResolver似乎没有实现Microsoft.Practices.ServiceLocation.IServiceLocator。
参数名称:commonServiceLocator

找到解决方案
也许有一种更优雅的方式,但现在这对我有用。我也在这里添加自定义消息处理程序。

[assembly: WebActivator.PreApplicationStartMethod(typeof(MyApp.AppStart.ApiBootstrapper), "Start")]
namespace MyApp.AppStart
{
    public class ApiBootstrapper
    {
        public static void Start()
        {
            var kernel = new StandardKernel(new MyNinjectModule());
            var resolver = new NinjectDependencyResolver(kernel);
            GlobalConfiguration.Configuration.ServiceResolver.SetResolver(resolver.GetService, resolver.GetServices);
            GlobalConfiguration.Configuration.MessageHandlers.Add(new ApiAuthHandler());
        }
    }
}

5 个答案:

答案 0 :(得分:3)

我从未使用过WebAPI,但由于IDependencyResolver的语义与MVC3的语义完全相同,因此您应该可以使用相同的实现:https://github.com/ninject/ninject.web.mvc/blob/master/mvc3/src/Ninject.Web.Mvc/NinjectDependencyResolver.cs

更新: Ninject.Web.WebAPi扩展添加了对ApiControllers

的支持

答案 1 :(得分:1)

我找到了答案并用解决方案更新了我的上述问题。解决方案本身或多或少存在于Using the Web API Dependency Resolver文章中,我只需要继续调整ninject。这两个答案帮助我迅速缩小了范围,感谢@Remo和@James。

答案 2 :(得分:0)

可能听起来很愚蠢,但您确定引用了CommonServiceLocator / CommonServiceLocator.NinjectAdapter nuget包或关联的程序集。您的NinjectDependencyResolver可能无法解析对IServiceLocator的引用。

答案 3 :(得分:0)

相同的代码适用于MVC和WebApi,但是因为WebApi受到MVC的启发,并且为了使用WebApi而不必引用MVC程序集(或反之亦然),因此有相当多的代码。两个框架之间的代码重复。如果你想使用MVC,你的依赖关系将来自System.Web.Mvc,如果你想使用WebApi,你将使用System.Web.Http。如果你想同时使用它们,你必须使用更明确的命名空间解析来区分你的代码。

在您的情况下,您的问题是MVC排在第一位,NinjectDependancyResolver类继承自System.Web.Mvc.IDependencyResolver。您需要创建NinjectDependancyResolver类的精确副本,而是继承System.Web.Http.IDependencyResolver。使用这个类来设置你的IoC,你会很高兴。

答案 4 :(得分:0)

我找到了一个很好的解决方案here

如果你已经在使用Ninject CommonServiceLocator / Bootstrapper,这很容易:

private static IKernel CreateKernel() {
   var kernel = new StandardKernel();
   RegisterServices(kernel);

   GlobalConfiguration.Configuration.ServiceResolver
      .SetResolver(new NinjectServiceLocator(kernel));
   return kernel; 
}