Skip to content

Providing another source of configuration for ReCaptcha

Jérémie Bertrand edited this page Mar 22, 2014 · 1 revision

ReCAPTCHA requires a public and private API key. You can specify these keys in your app's configuration, as follows:

<appSettings>
  <add key="reCAPTCHA::PublicKey" value="6LehOM0SAAAAAPgsjOy-6_grqy1JiB_W_jJa_aCw" />
  <add key="reCAPTCHA::PrivateKey" value="6LehOM0SAAAAAC5LsEpHoyyMqJcz7f_zEfqm66um" />
</appSettings>

But you can also provide a IConfigurationSource as a parameter for the constructors of ReCaptchaValidator and ReCaptchaGenerator. IConfiguration provides one method, which returns a value determined by a key in parameter:

string GetConfigurationValue(string key);

The ASP.NET DependencyResolver is used internally in order to retrieve the ReCaptchaGenerator, ReCaptchaValidator and the IConfigurationSource if necessary, so you have to use it or any IOC framework in order to indicates your own IConfigurationSource. Concrete example using Unity.MVC5 : The IConfigurationSource implementation:

public class MyConfigurationSource : IConfigurationSource
{
    public string GetConfigurationValue(string key)
    {
        string value = null;
        if(key == "reCAPTCHA::PublicKey")
        {
            value = "6LehOM0SAAAAAPgsjOy-6_grqy1JiB_W_jJa_aCw";
        }
        else if(key == "reCAPTCHA::PrivateKey")
        {
            value = "6LehOM0SAAAAAC5LsEpHoyyMqJcz7f_zEfqm66um";
        }
        return value;
    }
}

Using Unity as DependencyResolver:

var container = new UnityContainer();

container.RegisterType<IConfigurationSource, MyConfigurationSource>();

container.RegisterType<ICaptchaGenerator, ReCaptchaGenerator>();
container.RegisterType<ICaptchaValidator, ReCaptchaValidator>();

DependencyResolver.SetResolver(new UnityDependencyResolver(container));

So in this example the DepencyResolver use the Unity container to instantiate a ReCaptchaGenerator and a ReCaptchaValidator with an instance of MyConfigurationSource as parameter.