dapr / dotnet-sdk

Dapr SDK for .NET
Apache License 2.0
1.12k stars 340 forks source link

Allow access to injected services during DI registration of DaprClient #1288

Closed WhitWaldo closed 5 months ago

WhitWaldo commented 6 months ago

Describe the feature

Today, an extension method enables easy DI registration of the DaprClient on an IServiceCollection, but it doesn't allow for an IServiceProvider to be passed in so values can be pulled from injected dependencies. Having this option has some benefits - for example, say I'm passing in configuration values via a JSON file or via environment variables. I could trivially register the values for either in the service's IConfiguration (e.g. services.Configuration.AddEnvironmentVariables(); and recall via configuration.GetValue<string>("DAPR_HTTP_ENDPOINT"), but only if I can get an instance of the IConfiguration to get the values out of.

Where today, we might use the following:

var builder = WebApplication.CreateBuilder(args);
var httpEndpoint = Environment.GetEnvironmentVariable("DAPR_HTTP_ENDPOINT");
builder.Services.AddDaprClient(opt => {
  opt.UseHttpEndpoint(httpEndpoint);
});

This additional overload would also enable the following:

var builder = WebApplication.CreateBuilder(args);
builder.Configuration.AddEnvironmentVariables("DAPR_");
builder.Services.AddDaprClient((serviceProvider, daprClient) => {
  var configuration = serviceProvider.GetRequiredService<IConfiguration>();
  var httpEndpoint = configuration.GetValue<string>("HTTP_ENDPOINT");
  daprClient.UseHttpEndpoint(httpEndpoint);
});

I use it here to inject a value out of environment variables, but it could just as easily be a secret out of an Azure Key Vault instance or a value passed from Azure App Configuration or anything else that's registered in the application.

Release Note

RELEASE NOTE: ADD DaprClient dependency injection extension overload added to facilitate registration with dependencies

WhitWaldo commented 6 months ago

/assign