[csharp][restsharp] Add useClientFactory option to reuse HttpClient across requests

MR
1d ago
+68-3

ApiClient creates a new RestClient, and with it a new HttpClient, for every request. That is slow and can exhaust sockets under load. This adds an opt-in useClientFactory option that passes useClientFactory: true to the RestClient constructor, so RestSharp reuses one cached HttpClient per base URL. The default is false, which leaves generated output unchanged.

  • ApiClient.mustache / ApiClient.v790.mustache: pass the flag and re-apply configuration.UserAgent on each client. RestSharp only sets User-Agent when its factory first creates the HttpClient. Without the re-apply, every request after the first one to a base URL would go out without a User-Agent.
  • Caveat, also stated in the option description: the cached HttpClient is shared process-wide per base URL. Its handler-level settings (Proxy, ClientCertificates, UseDefaultCredentials, RemoteCertificateValidationCallback) come from the first request to that URL. Timeout, cookies and authenticators still apply per request.
  • The option is enabled in the csharp-restsharp-useVirtualForHooks sample. CSharpClientCodegenTest#testUseClientFactoryEmitsRestClientFactoryArgument covers both on and off.

Closes #25425
Related: #11271

PR checklist

  • Read the contribution guidelines.
  • Run the following to build the project and update samples:
    ./mvnw clean package || exit
    ./bin/generate-samples.sh ./bin/configs/*.yaml || exit
    ./bin/utils/export_docs_generators.sh || exit
    
    Commit all changed files.
  • If your PR is targeting a particular programming language, @mention the technical committee members, so they are more likely to review the pull request.

cc @mandrean @shibayan @Blackclaws @lucamazzanti


Summary by cubic

Adds an opt-in useClientFactory option to the C# RestSharp generator so the ApiClient reuses a cached HttpClient per base URL instead of creating one per request. The default is false, leaving generated output unchanged.

When enabled, RestSharp sets User-Agent only when the factory first creates the HttpClient, so the generated ApiClient re-applies configuration.UserAgent on every request. Handler-level settings (Proxy, client certificates, UseDefaultCredentials, RemoteCertificateValidationCallback) are fixed by the first request to a base URL; timeout, cookies, and authenticators still apply per request. Closes #25425.