Skip to content

Commit

Permalink
Throw an exception in ConfigureHttpClient when custom IForwarderHttpC…
Browse files Browse the repository at this point in the history
…lientFactory is already present (#1805)
  • Loading branch information
Kahbazi authored Aug 18, 2022
1 parent b3f464d commit 2f4f9e7
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

using System;
using System.Linq;
using System.Net.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection.Extensions;
Expand Down Expand Up @@ -143,6 +144,17 @@ public static IReverseProxyBuilder ConfigureHttpClient(this IReverseProxyBuilder
throw new ArgumentNullException(nameof(configure));
}

// Avoid overriding any other custom factories. This does not handle the case where a IForwarderHttpClientFactory
// is registered after this call.
var service = builder.Services.FirstOrDefault(service => service.ServiceType == typeof(IForwarderHttpClientFactory));
if (service is not null)
{
if (service.ImplementationType != typeof(ForwarderHttpClientFactory))
{
throw new InvalidOperationException($"ConfigureHttpClient will override the custom IForwarderHttpClientFactory type.");
}
}

builder.Services.AddSingleton<IForwarderHttpClientFactory>(services =>
{
var logger = services.GetRequiredService<ILogger<ForwarderHttpClientFactory>>();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace Yarp.ReverseProxy.Forwarder;

public class ReverseProxyServiceCollectionTests
{

[Fact]
public void ConfigureHttpClient_Works()
{
new ServiceCollection()
.AddReverseProxy()
.ConfigureHttpClient((_, _) => { });
}

[Fact]
public void ConfigureHttpClient_ThrowIfCustomServiceAdded()
{
Assert.Throws<InvalidOperationException>(() =>
{
new ServiceCollection()
.AddSingleton<IForwarderHttpClientFactory, CustomForwarderHttpClientFactory>()
.AddReverseProxy()
.ConfigureHttpClient((_, _) => { });
});
}

private class CustomForwarderHttpClientFactory : IForwarderHttpClientFactory
{
public HttpMessageInvoker CreateClient(ForwarderHttpClientContext context)
{
throw new NotImplementedException();
}
}
}

0 comments on commit 2f4f9e7

Please sign in to comment.