如何在ASP.NET CORE中将动作过滤器与依赖注入一起使用? [英] How to use Action Filters with Dependency Injection in ASP.NET CORE?

查看:338
本文介绍了如何在ASP.NET CORE中将动作过滤器与依赖注入一起使用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ASP.NET CORE应用程序中的任何地方都使用了基于构造函数的依赖注入,并且我还需要在操作过滤器中解析依赖:

I use constructor-based dependency injection everywhere in my ASP.NET CORE application and I also need to resolve dependencies in my action filters:

public class MyAttribute : ActionFilterAttribute
{
    public int Limit { get; set; } // some custom parameters passed from Action
    private ICustomService CustomService { get; } // this must be resolved

    public MyAttribute()
    {
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        // my code
        ...

        await next();
    }
}

然后在Controller中:

Then in Controller:

[MyAttribute(Limit = 10)]
public IActionResult()
{
    ...

如果将ICustomService放入构造函数,则无法编译我的项目.那么,我该如何在动作过滤器中获取接口实例呢?

If I put ICustomService to the constructor, then I'm unable to compile my project. So, how do I supossed to get interface instances in action filter?

推荐答案

如果要避免使用Service Locator模式,则可以通过构造函数注入TypeFilter来使用DI.

If you want to avoid the Service Locator pattern you can use DI by constructor injection with a TypeFilter.

在您的控制器中使用

[TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})]
public IActionResult() NiceAction
{
   ...
}

您的ActionFilterAttribute不再需要访问服务提供商实例.

And your ActionFilterAttribute does not need to access a service provider instance anymore.

public class MyActionFilterAttribute : ActionFilterAttribute
{
    public int Limit { get; set; } // some custom parameters passed from Action
    private ICustomService CustomService { get; } // this must be resolved

    public MyActionFilterAttribute(ICustomService service, int limit)
    {
        CustomService = service;
        Limit = limit;
    }

    public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
    {
        await next();
    }
}

对我来说,注释[TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})]似乎很尴尬.为了获得更易读的注释,例如[MyActionFilter(Limit = 10)],您的过滤器必须继承自TypeFilterAttribute.我对>我的答案在asp.net中向操作过滤器添加参数?显示了此方法的示例.

For me the annotation [TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})]seems to be awkward. In order to get a more readable annotation like [MyActionFilter(Limit = 10)]your filter has to inherit from TypeFilterAttribute. My answer of How do I add a parameter to an action filter in asp.net? shows an example for this approach.

这篇关于如何在ASP.NET CORE中将动作过滤器与依赖注入一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆