我在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中将动作过滤器与依赖注入一起使用?
发布评论