diff --git a/PoliteCaptcha/ReCaptchaGenerator.cs b/PoliteCaptcha/ReCaptchaGenerator.cs index ab2f112..6a9185a 100644 --- a/PoliteCaptcha/ReCaptchaGenerator.cs +++ b/PoliteCaptcha/ReCaptchaGenerator.cs @@ -12,7 +12,7 @@ namespace PoliteCaptcha /// public class ReCaptchaGenerator : ICaptchaGenerator { - readonly IConfigurationSource configSource; + readonly IConfigurationSource _configSource; public ReCaptchaGenerator() : this(new DefaultConfigurationSource()) @@ -21,7 +21,7 @@ public ReCaptchaGenerator() public ReCaptchaGenerator(IConfigurationSource configSource) { - this.configSource = configSource; + _configSource = configSource; } /// @@ -31,15 +31,16 @@ public ReCaptchaGenerator(IConfigurationSource configSource) /// An optional message to display above the CAPTCHA when it is displayed as a fallback. /// The reCAPTCHA HTML. public IHtmlString Generate( - HtmlHelper htmlHelper, + HtmlHelper htmlHelper, string fallbackMessage = null) { if (htmlHelper == null) + { throw new ArgumentNullException("htmlHelper"); + } - var configurationSource = DependencyResolver.Current.GetService(); - - var publicApiKey = configSource.GetConfigurationValue(Const.ReCaptchaPublicKeyAppSettingKey); + IConfigurationSource configurationSource = GetConfigurationSource(); + var publicApiKey = configurationSource.GetConfigurationValue(Const.ReCaptchaPublicKeyAppSettingKey); if (publicApiKey == null) { if (!htmlHelper.ViewContext.HttpContext.Request.IsLocal) @@ -68,9 +69,28 @@ public ReCaptchaGenerator(IConfigurationSource configSource) recaptchaControl.RenderControl(htmlWriter); var captchaHtml = htmlWriter.InnerWriter.ToString(); - var template = @"
{0}{1}
"; - + + const string template = @"
{0}{1}
"; return new MvcHtmlString(string.Format(template, fallbackMessage ?? Const.DefaulFallbackMessage, captchaHtml)); } + + private IConfigurationSource GetConfigurationSource() + { + if (_configSource != null) + { + return _configSource; + } + + if (DependencyResolver.Current != null) + { + var resolvedConfigSource = DependencyResolver.Current.GetService(); + if (resolvedConfigSource != null) + { + return resolvedConfigSource; + } + } + + return new DefaultConfigurationSource(); + } } }