Skip to content

0xced/Wcf.HttpClientFactory

Repository files navigation

Wcf.HttpClientFactory

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.

Getting Started

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.

  1. Install the dotnet-svcutil tool globally
dotnet tool install --global --verbosity normal dotnet-svcutil
  1. 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.

  1. Add the Wcf.HttpClientFactory NuGet package to your project using the NuGet Package Manager or run the following command:

⚠️ The NuGet package is not yet published.

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.

Configuring the SOAP client

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)

References

Related WCF issues:

About

No description, website, or topics provided.

Resources

License

Code of conduct

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published