Wcf.HttpClientFactory
is a library for using IHttpClientFactory
with the WCF client libraries, also known as System.ServiceModel.Http. Use IHttpClientFactory to implement resilient HTTP requests explains the shorcomings of HttpClient
and why using IHttpClientFactory
is important. In a nutshell, it avoids both the socket exhaustion problem and the DNS changes issue. More benefits are also explained in this article, don't hesitate to read it.
Since using IHttpClientFactory
is tightly coupled to Microsoft's dependency injection library, Wcf.HttpClientFactory
has been designed as an extension method (AddContract
) on IServiceCollection
.
This guide uses Learn Web Services, a free, public SOAP web service example.
The first step is to generate a C# SOAP client to access the Hello web service.
- Install the
dotnet-svcutil
tool globally
dotnet tool install --global --verbosity normal dotnet-svcutil
- Generate a client library project, named
HelloService
mkdir HelloService && cd HelloService
dotnet svcutil --targetFramework net8.0 --namespace "*, LearnWebServices" "https://apps.learnwebservices.com/services/hello?WSDL"
dotnet new classlib -f net8.0
rm Class1.cs
dotnet add package System.ServiceModel.Http
This generates the HelloEndpoint
interface and its associated HelloEndpointClient
implementation.
- Add the Wcf.HttpClientFactory NuGet package to your project using the NuGet Package Manager or run the following command:
dotnet add package Wcf.HttpClientFactory
Register the HelloEndpoint
interface in the dependency injection services collection with an associated configuration class which will be detailed below.
using LearnWebServices; // 👈 namespace of the generated SOAP client
using Wcf.HttpClientFactory; // 👈 for the AddContract extension method to be available
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddContract<HelloEndpoint, HelloServiceConfiguration>();
The AddContract
extension method accepts different parameters which all have a sensible default values. The xmldoc explains what they are in case you need to use a non default value. The AddContract
method returns an IHttpClientBuilder
so that delegating handlers can be configured, for example to implement resiliency with Polly or to tweak HTTP headers to workaround a non compliant HTTP server.
TODO:
- explain the configuration class, its DI benefits and its overridable methods
- explain how to inject and use
HelloEndpoint
(e.g. in a controller vs in a background service)
- Channel Factory and Caching
- Guidelines for using HttpClient — DNS behavior
- Avoid DNS issues with HttpClient in .NET
Related WCF issues: