diff --git a/Refit.Tests/HttpClientFactoryExtensionsTests.cs b/Refit.Tests/HttpClientFactoryExtensionsTests.cs index 87a73698c..586928cb4 100644 --- a/Refit.Tests/HttpClientFactoryExtensionsTests.cs +++ b/Refit.Tests/HttpClientFactoryExtensionsTests.cs @@ -1,11 +1,17 @@ -using Microsoft.Extensions.Options; - -namespace Refit.Tests; - +using System.Globalization; +using System.Net.Http; +using System.Reflection; using System.Text.Json; + using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +using Refit.Implementation; + using Xunit; +namespace Refit.Tests; + public class HttpClientFactoryExtensionsTests { class User { } @@ -154,6 +160,37 @@ public void HttpClientSettingsCanBeProvidedStaticallyGivenTypeArgument() ); } + [Fact] + public void ProvidedHttpClientIsUsedAsNamedClient() + { + var baseUri = new Uri("https://0:1337"); + var services = new ServiceCollection(); + + services.AddHttpClient("MyHttpClient", client => { + client.BaseAddress = baseUri; + client.DefaultRequestHeaders.Add("X-Powered-By", Environment.OSVersion.VersionString); + }); + services.AddRefitClient(null, "MyHttpClient"); + + var sp = services.BuildServiceProvider(); + var httpClientFactory = sp.GetRequiredService(); + var httpClient = httpClientFactory.CreateClient("MyHttpClient"); + + var gitHubApi = sp.GetRequiredService(); + + var memberInfos = typeof(Generated).GetMember("RefitTestsIGitHubApi", BindingFlags.NonPublic); + var genApi = Convert.ChangeType(gitHubApi, (Type)memberInfos[0], CultureInfo.InvariantCulture); + var genApiProperty = genApi.GetType().GetProperty("Client")!; + var genApiClient = (HttpClient)genApiProperty.GetValue(genApi)!; + + Assert.NotSame(httpClient, genApiClient); + Assert.Equal(httpClient.BaseAddress, genApiClient.BaseAddress); + Assert.Equal(baseUri, genApiClient.BaseAddress); + Assert.Contains( + new KeyValuePair>("X-Powered-By", + new[] { Environment.OSVersion.VersionString }), genApiClient.DefaultRequestHeaders); + } + class ClientOptions { public SystemTextJsonContentSerializer Serializer { get; set; }