title: Key store providers cannot be set more than once (Always Encryption using Azure Function )
body: <p>I've implemented a TimeTriggerC# Azure Function to Run a Store Procedure to an Insert a table that is Encrypted using Column Encryption(Always Encrypted, AzureKey Vault As Provider)</p>
  
  <p>The Blocking area for me is that my Function ran successfully at 1 time and got an error for again many times. So I get the success path as a rare case</p>
  
  <p>The Error I faced is </p>
  
  <blockquote>
    <p>mscorlib: Exception has been thrown by the target of an invocation.
    System.Data: Key store providers cannot be set more than once.</p>
  </blockquote>
  
  <p>I done some investigation on this It occurs in the line </p>
  
  <pre><code>SqlConnection.RegisterColumnEncryptionKeyStoreProviders(providers);
  </code></pre>
  
  <p>With in the function</p>
  
  <pre><code>static void InitializeAzureKeyVaultProvider()
  {
      string clientId = ConfigurationManager.AppSettings["AuthClientId"];
      string clientSecret = ConfigurationManager.AppSettings["AuthClientSecret"];
      _clientCredential = new ClientCredential(clientId, clientSecret);
  
      // Direct the provider to the authentication delegate
      SqlColumnEncryptionAzureKeyVaultProvider azureKeyVaultProvider = new SqlColumnEncryptionAzureKeyVaultProvider(GetToken);
  
      Dictionary&lt;string, SqlColumnEncryptionKeyStoreProvider&gt; providers = new Dictionary&lt;string, SqlColumnEncryptionKeyStoreProvider&gt;();
      providers.Add(SqlColumnEncryptionAzureKeyVaultProvider.ProviderName, azureKeyVaultProvider);
  
      // register the provider with ADO.net
      SqlConnection.RegisterColumnEncryptionKeyStoreProviders(providers);
  }
  </code></pre>
  
  <p>When I tried to look much deeper into the root cause of the error, it will be like</p>
  
  <blockquote>
    <p>Exception has been thrown by the target of an invocation. --->
    System.InvalidOperationException : Key store providers cannot be set
    more than once.    at
    System.Data.SqlClient.SqlConnection.RegisterColumnEncryptionKeyStoreProviders(IDictionary`2
    customProviders)</p>
  </blockquote>
  
  <p>As I mentioned above I used <strong>Azure Key Vault</strong> as my Key Store Provider.I properly registered my Keyvault with AD and added the registered application to my key vault (Access Policies).</p>
  
  <p>Why I'm facing this abnormal behavior, like one-time success and another time failure?</p>
  
  <p>Appreciate your Response,<br>
  Jayendran</p>