Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
public void ConfigureServices(IServiceCollection services)
// Maintain a single instance of the SocketsHttpHandler for the lifetime of the application
SocketsHttpHandler socketsHttpHandler = new SocketsHttpHandler();
socketsHttpHandler.PooledConnectionLifetime = TimeSpan.FromMinutes(10); // Customize this value based on desired DNS refresh timer
socketsHttpHandler.MaxConnectionsPerServer = 20; // Customize the maximum number of allowed connections
services.AddSingleton<CosmosClient>(serviceProvider =>
SocketsHttpHandler socketsHttpHandler = serviceProvider.GetRequiredService<SocketsHttpHandler>();
CosmosClientOptions cosmosClientOptions = new CosmosClientOptions()
HttpClientFactory = () => new HttpClient(socketsHttpHandler, disposeHandler: false)
return new CosmosClient("<connection-string>", cosmosClientOptions);
services.AddSingleton<OtherService>(serviceProvider =>
SocketsHttpHandler socketsHttpHandler = serviceProvider.GetRequiredService<SocketsHttpHandler>();
// another service that might also use HttpClient
HttpClient anotherHttpClient = new HttpClient(socketsHttpHandler, disposeHandler: false);
return new OtherService(anotherHttpClient);
//... other service registration
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment