ASP.NET MVC 5 Filter和Ninject

[英]ASP.NET MVC 5 Filter and Ninject

I have this DDD application that has MVC on the Presentation, with Ninject.


I have the CrossCutting Layer binding the injections from all the layers, and it works like a charm.

我有CrossCutting Layer綁定所有圖層的注入,它就像一個魅力。

What i can't make work, is when it comes to Filter Attributes. I have this filter that checks one cookie and depending on it's value, executes queries on the Database. With this Architecture, i just can't make my Filter access my Repository directly, it would be disrespectful to the methodology i'm applying.


I have my IFooAppService interface and have it's methods that eventually will hit the repository for Data requesting. I can successfully inject it in any Controller constructor and it will execute my _fooAppService.Query(), but i have this XooFilter above some actions in my application, and i just can't pass my _fooAppService to it. Here's my XooFilter:


public class XooFilter : ActionFilterAttribute
    private readonly IFooAppService _fooAppService;

    public XooFilter(IFooAppService fooAppService)
        _fooAppService = fooAppService;

    public override void OnActionExecuting(ActionExecutingContext filterContext)
        // LOGIC...

        var fooValue = _fooAppService.Query();

        // MORE LOGIC..

But, when i insert my filter above any Action [XooFilter], it won't work. It says the filter has no constructor with 0 elements.

但是,當我在任何Action [XooFilter]上面插入我的過濾器時,它將無法正常工作。它說過濾器沒有帶0個元素的構造函數。

I just can't figure it out how to do it nicely and keep the characteristics from DDD and IoC. I found the article below, but couldn't find any answer:


Injecting dependencies into ASP.NET MVC 3 action filters. What's wrong with this approach?

將依賴項注入ASP.NET MVC 3動作過濾器。這種方法有什么問題?

2 个解决方案


You could resolve your service this way


System.Web.Mvc.DependencyResolver.Current.GetService(typeof (IFooAppService ));


There's a Ninject extension package called Ninject.Web.Mvc (which you may already have). This allows you to set filter binding like so;


public class LoggingModule : NinjectModule
    public override void Load()
        this.BindFilter<LogFilter>(FilterScope.Controller, 0)
            .WithConstructorArgument("logLevel", Level.Info);

    private static ILog GetLogger(IContext ctx)
        var filterContext = ctx.Request.ParentRequest.Parameters

            LogManager.GetLogger(filterContext == null
                ? ctx.Request.Target.Member.DeclaringType
                : filterContext.ActionDescriptor.ControllerDescriptor.ControllerType);

Note the BindFilter method call. This works as of v.3.3.0.


Once configured, using it is like the usual constructor injection;


public class LogFilter : IActionFilter
    public LogFilter(ILog logger)
        // store your instance of "logger" here



粤ICP备14056181号  © 2014-2021