C# ActionAttribute DI
我不知道如何完成以下任务:C# ActionAttribute DI,c#,asp.net-core,C#,Asp.net Core,我不知道如何完成以下任务: 我有一个特点: public class Authorize : ActionFilterAttribute { private readonly IAccessPermissionRepository _repository; public Authorize(IAccessPermissionRepository repository) { _repository = repository;
我有一个特点:
public class Authorize : ActionFilterAttribute
{
private readonly IAccessPermissionRepository _repository;
public Authorize(IAccessPermissionRepository repository)
{
_repository = repository;
}
...
}
默认情况下,IAccessPermissionRepository是解析的
我在控制器类中使用它,就像这样
[ServiceFilter(typeof(Authorize))]
public IActionResult Index()
但现在我想把额外的参数传递给构造函数,每个动作和控制器都不同。通常我只会使用构造函数,但是。。您可以看到。您使用TypeFilter而不是ServiceFilter,如下所示:
[TypeFilter(typeof(HasDummyPrivilegeAttribute), Arguments = new object[] { "dummyId" })]
HasDummyPrivilegeAttribute看起来像:
public class HasDummyPrivilegeAttribute : ActionFilterAttribute
{
private readonly string _idParameterName;
private readonly IAccessPermissionRepository _repo;
public HasServicePrivilegeAttribute(
string idParameterName,
[FromServices] IAccessPermissionRepository repo)
{
_idParameterName = idParameterName;
_repo = repo;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
//TODO Something awesome here with _idParameterName and _repo
}
}
这是一个较老的讨论,我对Core不太熟悉,无法提供更多的见解,但我的问题似乎和你一样,并且在评论中有一个变通方法。谢谢,我不敢相信我错过了那个。我不会太担心它。它的文档很糟糕,语法也很糟糕。