如何在ASP.NET CORE中将动作过滤器与依赖注入一起使用?

编程入门 行业动态 更新时间:2024-10-23 21:29:48
本文介绍了如何在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中向操作过滤器添加参数?显示了此方法的示例.

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? shows an example for this approach.

更多推荐

如何在ASP.NET CORE中将动作过滤器与依赖注入一起使用?

本文发布于:2023-11-14 13:39:12,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587366.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:过滤器   中将   动作   如何在   CORE

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!