我在我的 ASP.NET CORE
应用程序中到处使用基于构造函数的依赖注入(inject),我还需要在我的操作过滤器中解析依赖关系:
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 中:
[MyAttribute(Limit = 10)]
public IActionResult()
{
...
如果我将 ICustomService 放入构造函数,那么我将无法编译我的项目。那么,我应该如何在 Action 过滤器中获取接口(interface)实例呢?
最佳答案
如果您想避免使用服务定位器模式,您可以通过带有 TypeFilter
的构造函数注入(inject)来使用 DI。
在你的 Controller 中使用
[TypeFilter(typeof(MyActionFilterAttribute), Arguments = new object[] {10})]
public IActionResult() NiceAction
{
...
}
并且您的ActionFilterAttribute
不再需要访问服务提供者实例。
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
。我对How do I add a parameter to an action filter in asp.net?的回答显示了这种方法的示例。
关于c# - 如何在 ASP.NET CORE 中使用具有依赖注入(inject)的 Action 过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39256341/