好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Ninject对Web Api的支持问题

Ninject对Web Api的支持问题

问题描述:

昨天将MVC从3升级到了4,主要是想利用其中的Web Api功能。创建了一个继承自ApiController的控制器,并且跟以前普通控制器一样,构造函数的参数采用Ninject进行依赖注入。之后调用其中某个方法,却发现提示这个控制器没有默认构造函数,经过搜索,发现Ninject目前不直接支持对ApiController的依赖注入,仅仅支持普通控制器(继承自Controller)。

解决方法:
google了一下,发现有很多文章介绍解决方法,都是如下思路:

1.nuget安装Ninject.Web.WebApi包

2.在global.asax中设定:

  GlobalConfiguration.Configuration.DependencyResolver = new NinjectDependencyResolver(kernel); 
然而如此操作后发现第二步骤这个代码根本无法成功编译,提示两个类型并没有隐式转换关系。

经过半天的问题查找,终于发现,以上这个方法已经不再支持最新版本的ASP.NET Web API,如果当前版本WebApi是rc及以上,则上面方法就不再试用。然而,即使是Codeplex目前最新的(9.23日为止)Ninject或Ninject.Web.WebApi都尚未支持新的WebApi。

实际上二月份ASP.NET Web API  beta出来时,许多IoC都公布了支持WebApi方法,也就是利用IDependencyResolver适配器来实现支持,上面那个方法就是这时候出来的。

目前如果想Ninject支持最新版Web Api,有一个解决方法:

1.卸载Ninject.Web.WebApi,nuget上安装Ninject.MVC3(是的,他也支持MVC4)包。

2.定义两个类,用于实现最新版Web Api要求的IDependencyResolver:

?

public   class   NinjectScope : IDependencyScope

     {

         protected   IResolutionRoot resolutionRoot;

 

         public   NinjectScope(IResolutionRoot kernel)

         {

             resolutionRoot = kernel;

         }

 

         public   object   GetService(Type serviceType)

         {

             IRequest request = resolutionRoot.CreateRequest(serviceType, null , new   Parameter[0], true , true );

             return   resolutionRoot.Resolve(request).SingleOrDefault();

         }

 

         public   IEnumerable< object > GetServices(Type serviceType)

         {

             IRequest request = resolutionRoot.CreateRequest(serviceType, null , new   Parameter[0], true , true );

             return   resolutionRoot.Resolve(request).ToList();

         }

 

         public   void   Dispose()

         {

             IDisposable disposable = (IDisposable)resolutionRoot;

             if   (disposable != null ) disposable.Dispose();

             resolutionRoot = null ;

         }

     }

?

public   class   NinjectResolver : NinjectScope, IDependencyResolver

{

private   IKernel _kernel;

public   NinjectResolver(IKernel kernel)

: base (kernel)

{

_kernel = kernel;

}

public   IDependencyScope BeginScope()

{

return   new   NinjectScope(_kernel.BeginBlock());

}

}

3.在NinjectWebCommon.cs或Global.asax中,添加如下代码,注册上面的支持WebApi的解析器

GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(kernel);

这样,此问题得到解决。其他的Ioc,比如Autofac,也有类似解决方式,查找答案时,应注意版本支持。

经验:

升级某一个框架要谨慎,看其他相关框架是否同步支持这一升级。

开源软件选择很重要,一旦停止或很久不更新,将导致整体项目迁移困难。

参考:

<Issue using ASP.Net MVC 4 Web API with Ninject.Web.WebApi>

<Using Ninject with the latest ASP.NET Web API source>

作者: lerit

出处: http://www.cnblogs.com/lerit/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利.

作者: Leo_wl

    

出处: http://www.cnblogs.com/Leo_wl/

    

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

版权信息

查看更多关于Ninject对Web Api的支持问题的详细内容...

  阅读:38次