我试图将一个服务注入我的动作过滤器,但我没有在构造函数中注入所需的服务.这是我有的:
public class EnsureUserLoggedIn : ActionFilterAttribute
{
private readonly ISessionService _sessionService;
public EnsureUserLoggedIn()
{
// I was unable able to remove the default ctor
// because of compilation error while using the
// attribute in my controller
}
public EnsureUserLoggedIn(ISessionService sessionService)
{
_sessionService = sessionService;
}
public override void OnActionExecuting(ActionExecutingContext context)
{
// Problem: _sessionService is null here
if (_sessionService.LoggedInUser == null)
{
context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Result = new JsonResult("Unauthorized");
}
}
}
Run Code Online (Sandbox Code Playgroud)
而我正在装饰我的控制器:
[Route("api/issues"), EnsureUserLoggedIn]
public class IssueController : …Run Code Online (Sandbox Code Playgroud) 我在我的ASP.NET CORE应用程序中使用基于构造函数的依赖注入,我还需要在我的动作过滤器中解决依赖关系:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后在控制器中:
[MyAttribute(Limit = 10)]
public IActionResult()
{
...
Run Code Online (Sandbox Code Playgroud)
如果我把ICustomService放到构造函数中,那么我就无法编译我的项目了.那么,我如何在动作过滤器中获取接口实例呢?
ServiceFilter我们必须在Startup.cs中注册.TypeFilter是由Microsoft.Extensions.DependencyInjection.ObjectFactory注入的,我们不需要注册那个过滤器.
那么当我们应该使用ServiceFilter和TypeFilter时?