mercredi 16 juin 2021

HttpClientFactory and Options Pattern

I have a dotnet5 isolated host azure function. I'm trying to implement the use of the Options Pattern for config settings as described here

In program.main, I have added the following and this works well:

var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults()
            .ConfigureServices(s =>
            {
            s.AddOptions<UtrnOptions>()
                .Configure<IConfiguration>((settings, configuration) =>
                {
                    configuration.GetSection("Utrn").Bind(settings);
                })

An instance of the UtrnOptions class can now be injected into any constructor and I'm able to reference config values such as utrnOptions.GenSvcBaseAddress

My problem is I also need to to register typed clients using IHttpClientFactory. Previously, I used an extension mehtod (named AddUtrnSvcHttpClient) that I included in the lambda for .ConfigureServices as shown below:

.ConfigureServices(s =>
            {
                s.AddTransient<IUtrnSvc, UtrnSvc>();
                //add typed client for http factory
                s.AddUtrnSvcHttpClient(configTokens);

The "configTokens" parameter of the extension method was a dictionary that had been populated with config from local.settings.json (or the runtime env variables when running in Azure).

How can I get an instance of the UtrnOptions class into the extension method? I can't use constructor injection because extension methods needs to be static.

Does anyone know of a repo that makes use of the options pattern and HttpClientFactory Typed Clients?

Aucun commentaire:

Enregistrer un commentaire