如何在 ActionFilterAttribute 中注入依赖

How to Inject Dependency in ActionFilterAttribute

我正在使用此代码在我的 ASP.Net MVC 5 页面上实现 Google 的 reCaptcha:

https://www.c-sharpcorner.com/blogs/google-recaptcha-in-asp-net-mvc

    public class ValidateGoogleCaptchaAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            const string urlToPost = "https://www.google.com/recaptcha/api/siteverify";
            var captchaResponse = filterContext.HttpContext.Request.Form["g-recaptcha-response"];

            if (string.IsNullOrWhiteSpace(captchaResponse)) AddErrorAndRedirectToGetAction(filterContext);

            var validateResult =
                ValidateFromGoogle(urlToPost, GoogleReCaptchaVariables.ReCaptchaSecretKey, captchaResponse);
            if (!validateResult.Success) AddErrorAndRedirectToGetAction(filterContext);

            base.OnActionExecuting(filterContext);
        }

这段代码的问题在于,该网站无法访问互联网,无法直接调用Google的API,必须通过内部服务, IReCaptcha,通过Unity.MVC:

注入整个系统

container.RegisterType<IReCaptcha, ReCaptcha>();

问题是:如何将 IReCaptcha 注入 ValidateGoogleCaptchaAttribute?

似乎唯一的解决办法是获取当前的 DependencyResolver 并手动获取服务:

var reCaptcha = DependencyResolver.Current.GetService(typeof(IReCaptcha)) as IReCaptcha;

我相信这应该适用于任何地方。