title: Get Key Vault ServiceClient within Program.cs (startup) in a .NET 6 app
body: <p>I've been Googling for hours without success and hopefully someone here can help me out. I created an Entity Framework DbContext which I initialize in the Program (Startup.cs is not needed anymore in .NET 6). The connectionstring is dependent on a SQL password inside Azure Key Vault. So the registration of both Key Vault and DbContext are done in the Program.cs . But how do I retrieve the secret from KeyVault to put inside the connectionstring? I do not want to manually create a SecretClient instance here, but have it injected somehow...</p>
  <p>I now have:</p>
  <pre><code>builder.Services.AddAzureClients(clientBuilder =&gt;
  {
      clientBuilder.AddSecretClient(new Uri(builder.Configuration.GetSection(&quot;KeyVault:VaultUri&quot;).Value))
          .WithCredential(new DefaultAzureCredential());
  });
  builder.Services.AddDbContext&lt;MyContext&gt;(options =&gt;
  {
      // How to get an instance of SecretClient here via DI? I need to call the serviceClient.GetSecret(&quot;sql-password&quot;) here to put it inside the connectionstring
      // var sqlPassword = builder.Configuration.GetSection(&quot;sql-password&quot;).Value &lt;-- also returns null
      var sqlPassword = &quot;get-this-password-from-key-vault&quot;;
      options.UseSqlServer(string.Format(builder.Configuration.GetConnectionString(&quot;MyConnectionString&quot;), sqlPassword));
  });
  </code></pre>
  <p>I've read on several blogs that when you add the SecretClient to the Services, it should read all the secrets and add them to the builder.Configuration , meaning you should be able to read it like this:</p>
  <pre><code>var sqlPassword = builder.Configuration[&quot;sql-password&quot;]
  </code></pre>
  <p>or</p>
  <pre><code>var sqlPassword = builder.Configuration.GetSection(&quot;sql-password&quot;).Value
  </code></pre>
  <p>Both of them return <strong>null</strong> . So I'm running out of options here. If anyone has a solution for this simple problem, I'm more than grateful. Thanks!</p>
  <p>PS: I know for a fact the Key Vault is registrered succesfully; when I use the ServiceClient within a controller, I can successfully retrieve the secret.</p>