Filter constructor injection using Ninject

后端 未结 3 2144
我寻月下人不归
我寻月下人不归 2021-02-08 04:30

I am trying to find a way to use Ninject to inject constructor dependencies into filters. I am finding many articles describing property injection which is now advised against,

3条回答
  •  情歌与酒
    2021-02-08 04:42

    There is a way to use constructor injection.

    First you replace your attribute with an 'empty' one which you will just use as a marker

    public class UserValidationAttribute : Attribute { }
    

    Then you create a filter class as an IActionFilter.

    public class UserValidationFilter : IActionFilter
    {
        private readonly IRepository repository;
    
        public UserValidationFilter(IRepository repository)
        {
            this.repository = repository;
        }
    
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //do something
        }
    
        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            //do something
        }      
    }
    

    Then you can register it with something like

    private static void RegisterServices(IKernel kernel)
    {
        kernel.BindFilter(FilterScope.Action, 0)
            .WhenActionMethodHas();
    }
    

    If your attribute itself has constructor parameters, you can pass them in like

    kernel.BindFilter(FilterScope.Action, 0)
        .WhenActionMethodHas();
        .WithConstructorArgumentFromActionAttribute("myParameter", attr => attr.MyParameter);
    

    The BindFilter syntax is part of Ninject.Web.Mvc.FilterBindingSyntax.

提交回复
热议问题