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:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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 ;
         }
     }

 本文来自http://zq229988.com/zuqiuzixun/

?
1
2
3
4
5
6
7
8
9
10
11
12
13
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,也有类似解决方式,查找答案时,应注意版本支持。

 

经验:

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

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

 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值