How can I use Dependency Injection in a .Net Core ActionFilterAttribute?

前端 未结 2 1079
灰色年华
灰色年华 2020-12-03 04:59

AuthenticationRequiredAttribute Class

public class AuthenticationRequiredAttribute : ActionFilterAttribute
{
    ILoginTokenKeyApi _loginTo         


        
2条回答
  •  南方客
    南方客 (楼主)
    2020-12-03 05:49

    Instead of resolving at construction, ActionExecutingContext.HttpContext.RequestServices should give you a reference to the request's service container at the time of the request.

    So:

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var svc = filterContext.HttpContext.RequestServices;
        var memCache = svc.GetService();
        //..etc
    

提交回复
热议问题