Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddSingleton<CosmosClient>(serviceProvider =>
{
IHttpClientFactory httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
{
HttpClientFactory = httpClientFactory.CreateClient,
ConnectionMode = ConnectionMode.Gateway
};
return new CosmosClient("<connection-string>", cosmosClientOptions);
});
//... other service registration
}
@ylr-research

This comment has been minimized.

Copy link

@ylr-research ylr-research commented Sep 19, 2020

I tried this approach and got an error. See below error and Main method

image

        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
            builder.Services.AddHttpClient();
            builder.Services.AddSingleton<CosmosClient>(serviceProvider =>
            {
                IHttpClientFactory httpClientFactory = serviceProvider.GetRequiredService<IHttpClientFactory>();

                CosmosClientOptions cosmosClientOptions = new CosmosClientOptions
                {
                    HttpClientFactory = httpClientFactory.CreateClient,
                    ConnectionMode = ConnectionMode.Gateway
                };

                return new CosmosClient("<connection-string>", cosmosClientOptions);
            });
            builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");

            await builder.Build().RunAsync();
        }
@ealsur

This comment has been minimized.

Copy link
Owner Author

@ealsur ealsur commented Sep 21, 2020

@ylr-research

My code example has services.AddHttpClient();, how are you registering the IHttpClientFactory?

You are just creating a Transient instance of HttpClient, which that by itself is incorrect, you should avoid creating new HttpClients all the time.

@ylr-research

This comment has been minimized.

Copy link

@ylr-research ylr-research commented Sep 21, 2020

@ealsur I fixed those lines already an the error is still the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment