Search code examples
c#azuredependency-injectionazure-functionsnuget-package

Is there anyway to use the AddSecretClient DI extension in an azure function?


I'm trying to configure some depedancies for my azure function. I need to be able to access (among other things) an azure keyvault. Currently I'm accessing this manually and having to do all my own dependancy injection. This didn't feel right and I went looking for a better way to hook this up. I found this blog that seems ideal.

public void ConfigureServices(IServiceCollection services)
{
  services.AddAzureClients(builder =>
  {
    // Add a KeyVault client
    builder.AddSecretClient(keyVaultUrl);

    // Add a storage account client
    builder.AddBlobServiceClient(storageUrl);

    // Use the environment credential by default
    builder.UseCredential(new EnvironmentCredential());
  });

  services.AddControllers();
}

Great I want to do that. Problem is these extensions don't seem to support the particular DI implemented in Azure functions. Specifically there is an incompatibility between the type expected for the AddSecretClient and the builder injected into the Configure(IFunctionsHostBuilder builder):

[assembly: FunctionsStartup(typeof(Startup))]
namespace Snapshot.Take
{
    [ExcludeFromCodeCoverage]
    public class Startup : FunctionsStartup
    {
        

        public override void Configure(IFunctionsHostBuilder builder)
        {
            RegisterHttpClients(builder);

            builder.Services.AddLogging();

            //error

            builder.AddSecretClient(new Uri(""));
       }
   }
}

The type 'Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder' cannot be used as type parameter 'TBuilder' in the generic type or method 'SecretClientBuilderExtensions.AddSecretClient(TBuilder, Uri)'. There is no implicit reference conversion from 'Microsoft.Azure.Functions.Extensions.DependencyInjection.IFunctionsHostBuilder' to 'Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential'.

So is there an Azure function version of these extensions or do I have to roll my own?


Solution

  • Since AddAzureClients is an extension method on IServiceCollection, you'll probably need to do something like:

      builder.Services.AddAzureClients(clientBuilder =>
      {
        // Add a KeyVault client
        clientBuilder.AddSecretClient(keyVaultUrl);
    
        // Add a storage account client
        clientBuilder.AddBlobServiceClient(storageUrl);
    
        // Use the environment credential by default
        clientBuilder.UseCredential(new EnvironmentCredential());
      });