在webapi actionfilter

时间:2016-05-17 20:16:18

标签: c# asp.net-web-api asp.net-web-api2 ninject

我已经获得了一个webapi2应用程序来管理,我已经开始为它编写一些单元测试,因为它没有。

测试控制器和服务都非常容易,因为它们是通过构造函数注入注入它们的依赖项。

对于actionfilters,我看到事情的完成方式不同,因为无法使用构造函数注入。

现在我还没有真正使用过ninject,但这是一个如何设置过滤器的例子。

public class CustomFilterAttribute : ActionFilterAttribute
{
    public ILog Log { get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        var id = int.Parse(actionContext.ActionArguments["id"].ToString());
        Log = actionContext.Request
            .GetDependencyScope()
            .GetService(typeof(ILog))
            as ILog;


     Log.WriteMessage(string.Format("Got id:{0}",id));

   }
}

我的注册类似

kernel.Bind<ILog>().ToConstant(new Log());

这看起来不错吗?我不确定如何为过滤器编写测试,我是否需要模拟.GetDependencyScope以包含我所需的ILog

日志在过滤器中连接的方式是正确的吗?

1 个答案:

答案 0 :(得分:0)

要通过DependencyResolver访问它,您需要使用http配置注册它。

public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver, System.Web.Mvc.IDependencyResolver {
   private readonly IKernel kernel;

   public NinjectDependencyResolver(IKernel kernel)
       : base(kernel) {
       this.kernel = kernel;
   }

   public IDependencyScope BeginScope() {
       return new NinjectDependencyScope(this.kernel.BeginBlock());
   }
}

然后在启动期间注册它......

// Use the kernal and the NinjectDependencyResolver as
// application's resolver
var resolver = new NinjectDependencyResolver(kernal);

//Register Resolver for Web Api
GlobalConfiguration.Configuration.DependencyResolver = resolver;

您可以通过ActionContext

访问解析程序
public class CustomFilterAttribute : ActionFilterAttribute {
    public ILog Log { get; set; }

    public override void OnActionExecuting(HttpActionContext actionContext) {
        var id = int.Parse(actionContext.ActionArguments["id"].ToString());
        Log = actionContext
            .RequestContext
            .Configuration
            .DependencyResolver
            .GetService(typeof(ILog))
            as ILog;


       Log.WriteMessage(string.Format("Got id:{0}",id));
   }
}