【发布时间】:2018-11-27 23:28:51
【问题描述】:
我需要通过依赖注入向操作过滤器注入一些服务。我熟悉 [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");
}
看起来很不一样,这种方法对我来说似乎不合适。
【问题讨论】:
-
您的过滤器使用 DI 吗?还有你所说的“正常方式”是什么意思?
-
@Shyju 是的,它确实使用 DI。 “正常方式” - 我的意思是没有 [ServiceFilter] 和 [TypeFilter] 包装我正在使用的过滤器。
-
如果您的文件管理器中有 DI,这就是使用它的方法。我认为这是“正常方式”
-
没有其他办法了。 DI/IoC 容器不是黑魔法。就其本质而言,必须使用已知参数来实例化属性(必须在编译时知道参数 - 这是 CIL/语言限制),这意味着只有常量。当然,您可以在 OnActionXxx 方法中访问
context.HttpContext.RequestServices.GetRequiredService<IMyService>();,但这也不是很干净,当然,它不再称为依赖注入 -
您可以为您的 first 示例实现
IFilterFactory(不带参数)。
标签: c# asp.net-core dependency-injection asp.net-core-mvc asp.net-core-2.1