没有[ServiceFilter]或[TypeFilter]的过滤器中的Asp.net Core依赖项注入

时间:2018-11-27 23:28:52

标签: c# asp.net-core dependency-injection asp.net-core-mvc asp.net-core-2.1

我需要将一些具有依赖项注入的服务注入到动作过滤器中。我对[ServiceFilter][TypeFilter]方法很熟悉,但这有点丑陋,混乱且不清楚。

有没有一种方法可以正常设置过滤器?而不包装[ServiceFilter][TypeFilter]使用的过滤器?

例如我想要的:

[SomeFilterWithDI]
[AnotherFilterWithDI("some value")]
public IActionResult Index()
{
    return View("Index");
}

代替:

[ServiceFilter(typeof(SomeFilterWithDI))]
[TypeFilter(typeof(AnotherFilterWithDI), Arguments = new string[] { "some value" })]
public IActionResult Index()
{
    return View("Index");
}

看起来很不一样,这种方法对我来说似乎不正确。

1 个答案:

答案 0 :(得分:1)

对于[SomeFilterWithDI],您可以参考@Kirk larkin的评论。

对于[AnotherFilterWithDI("some value")],您可以尝试从Arguments传递TypeFilterAttribute

  • ParameterTypeFilter定义接受参数。

    public class ParameterTypeFilter: TypeFilterAttribute
    {
    
        public ParameterTypeFilter(string para1, string para2):base(typeof(ParameterActionFilter))
        {
            Arguments = new object[] { para1, para2 };
        }
    }
    
  • ParameterActionFilter接受传递的参数。

        public class ParameterActionFilter : IActionFilter
    {
        private readonly ILogger _logger;
        private readonly string _para1;
        private readonly string _para2;
    
        public ParameterActionFilter(ILoggerFactory loggerFactory, string para1, string para2)
        {
            _logger = loggerFactory.CreateLogger<ParameterTypeFilter>();
            _para1 = para1;
            _para2 = para2;
        }
    
        public void OnActionExecuting(ActionExecutingContext context)
        {
            _logger.LogInformation($"Parameter One is {_para1}");
            // perform some business logic work
    
        }
    
        public void OnActionExecuted(ActionExecutedContext context)
        {
            // perform some business logic work
            _logger.LogInformation($"Parameter Two is {_para2}");
        }
    }
    

    作为Arguments的描述,ILoggerFactory loggerFactorydependency injection container解析。 para1para2ParameterTypeFilter解析。

        //
    // Summary:
    //     Gets or sets the non-service arguments to pass to the Microsoft.AspNetCore.Mvc.TypeFilterAttribute.ImplementationType
    //     constructor.
    //
    // Remarks:
    //     Service arguments are found in the dependency injection container i.e. this filter
    //     supports constructor injection in addition to passing the given Microsoft.AspNetCore.Mvc.TypeFilterAttribute.Arguments.
    public object[] Arguments { get; set; }
    
  • 使用情况

    [ParameterTypeFilter("T1","T2")]
    public ActionResult Parameter()
    {
        return Ok("Test");
    }