{"id":20040021,"url":"https://github.com/wilsonneto-dev/demo-httpclient-factory","last_synced_at":"2025-03-02T06:42:07.383Z","repository":{"id":244721294,"uuid":"816059457","full_name":"wilsonneto-dev/demo-httpclient-factory","owner":"wilsonneto-dev","description":"A demo on how to use HttpClient factory (Named HttpClients, Typed HttpClients, IHttpClientFactory)","archived":false,"fork":false,"pushed_at":"2024-06-17T00:53:07.000Z","size":18,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-01-12T19:14:15.395Z","etag":null,"topics":["dotnet","dotnet-core","httpclientfactory"],"latest_commit_sha":null,"homepage":"","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wilsonneto-dev.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-06-17T00:15:39.000Z","updated_at":"2024-06-17T00:53:10.000Z","dependencies_parsed_at":"2024-06-17T01:36:01.043Z","dependency_job_id":"629802ae-0b06-4012-be6d-c021426009e9","html_url":"https://github.com/wilsonneto-dev/demo-httpclient-factory","commit_stats":null,"previous_names":["wilsonneto-dev/demo-httpclient-factory"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wilsonneto-dev%2Fdemo-httpclient-factory","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wilsonneto-dev%2Fdemo-httpclient-factory/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wilsonneto-dev%2Fdemo-httpclient-factory/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wilsonneto-dev%2Fdemo-httpclient-factory/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wilsonneto-dev","download_url":"https://codeload.github.com/wilsonneto-dev/demo-httpclient-factory/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":241470311,"owners_count":19968041,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dotnet","dotnet-core","httpclientfactory"],"created_at":"2024-11-13T10:40:06.973Z","updated_at":"2025-03-02T06:42:07.361Z","avatar_url":"https://github.com/wilsonneto-dev.png","language":"C#","funding_links":[],"categories":[],"sub_categories":[],"readme":"## IHttpClientFactory - Demo\n\nThis repo is an example of the best ways of using HttpClient and IHttpClientfactory.\n\nInstantiating HttpClients directly in the components that will use it (not recommended):\n\n```csharp\n\ninternal class OpenAiGateway(IOptions\u003cOpenAiSettings\u003e openAiSettings)\n{\n    private readonly string _baseAddress = openAiSettings.Value.BaseAddress;\n    private readonly string _apiKey = openAiSettings.Value.ApiKey;\n\n    public async Task\u003cstring\u003e ExecutePrompt(string prompt)\n    {\n        var client = new HttpClient { BaseAddress = new (_baseAddress) };\n        client.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {_apiKey}\");\n\n        var httpResponse = await client.PostAsJsonAsync(\"chat/completions\", \n            new CompletionsRequest(\"gpt-4o\", [ new Message(\"user\", prompt) ]));\n\n        var response = await httpResponse.Content.ReadFromJsonAsync\u003cCompletionsResponse\u003e();\n\n        return response!.Choices[0].Message.Content;\n    }\n}\n\n```\n\nInstantiating HttpClients using factory, but it still in the components that will use it (not recommended):\n\n```csharp\n\nbuilder.Services.AddHttpClient();\n\n// ...\n\ninternal class OpenAiGateway\n{\n    private readonly HttpClient _httpClient;\n\n    public OpenAiGateway(IOptions\u003cOpenAiSettings\u003e openAiSettings, IHttpClientFactory httpClientFactory)\n    {\n        _httpClient = httpClientFactory.CreateClient();\n        _httpClient.BaseAddress = new (openAiSettings.Value.BaseAddress);\n        _httpClient.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {openAiSettings.Value.ApiKey}\");\n    }\n\n    public async Task\u003cstring\u003e ExecutePrompt(string prompt)\n    {\n        var httpResponse = await _httpClient.PostAsJsonAsync(\"chat/completions\", \n            new CompletionsRequest(\"gpt-4o\", [ new Message(\"user\", prompt) ]));\n\n        var response = await httpResponse.Content.ReadFromJsonAsync\u003cCompletionsResponse\u003e();\n        \n        return response!.Choices[0].Message.Content;\n    }\n}\n\n```\n\nNamed HttpClients (recommended):\n\n```csharp\n\n// to add\n\n```\n\nTyped HttpClients (recommended):\n\n```csharp\n\nservices.AddSingleton\u003cIValidateOptions\u003cOpenAiSettings\u003e, OpenAiSettingsValidate\u003e();\nservices.AddOptionsWithValidateOnStart\u003cOpenAiSettings\u003e()\n    .Bind(configuration);\n\nservices.AddTransient\u003cOpenAiGateway\u003e();\n\nservices.AddHttpClient\u003cOpenAiGateway\u003e((serviceProvider, httpClient) =\u003e\n{\n    var openAiSettings = serviceProvider.GetRequiredService\u003cIOptions\u003cOpenAiSettings\u003e\u003e();\n    httpClient.BaseAddress = new (openAiSettings.Value.BaseAddress);\n    httpClient.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {openAiSettings.Value.ApiKey}\");\n});\n\n// ...\n\ninternal class OpenAiGateway(HttpClient httpClient)\n{\n    public async Task\u003cstring\u003e ExecutePrompt(string prompt)\n    {\n        var httpResponse = await httpClient.PostAsJsonAsync(\"chat/completions\", \n            new CompletionsRequest(\"gpt-4o\", [ new Message(\"user\", prompt) ]));\n\n        var response = await httpResponse.Content.ReadFromJsonAsync\u003cCompletionsResponse\u003e();\n        \n        return response!.Choices[0].Message.Content;\n    }\n}\n\n```\n\nMessage handler example:\n\n```csharp\n\nservices.AddHttpClient\u003cOpenAiGateway\u003e((serviceProvider, httpClient) =\u003e\n{\n    var openAiSettings = serviceProvider.GetRequiredService\u003cIOptions\u003cOpenAiSettings\u003e\u003e();\n    httpClient.BaseAddress = new (openAiSettings.Value.BaseAddress);\n    httpClient.DefaultRequestHeaders.Add(\"Authorization\", $\"Bearer {openAiSettings.Value.ApiKey}\");\n})\n    .AddHttpMessageHandler\u003cLoggingHandler\u003e();\n\n// ...\n\npublic class LoggingHandler(ILogger\u003cLoggingHandler\u003e logger) : DelegatingHandler\n{\n    protected override async Task\u003cHttpResponseMessage\u003e SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)\n    {\n        logger.LogInformation(\"Request: {Body}\", await request.Content!.ReadAsStringAsync());\n\n        var response = await base.SendAsync(request, cancellationToken);\n        \n        logger.LogInformation(\"StatusCode: {StatusCode}\", response.StatusCode);\n        var responseContent = await response.Content.ReadAsStringAsync();\n        logger.LogInformation(\"Content: {Content}\", responseContent);\n        \n        return response;\n    }\n}\n\n```\n\nThis demo uses:\n- .Net 9\n\n---\n\n| [\u003cimg src=\"https://github.com/wilsonneto-dev.png\" width=\"75px;\"/\u003e][1] |\n| :-: |\n|[Wilson Neto][1]|\n\n\n[1]: https://github.com/wilsonneto-dev\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwilsonneto-dev%2Fdemo-httpclient-factory","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwilsonneto-dev%2Fdemo-httpclient-factory","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwilsonneto-dev%2Fdemo-httpclient-factory/lists"}