IC Improve Code Recipes

Recipe 13.4 · Python

Calling Legacy SOAP and WCF Services

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

The rates service, the policy-admin system or the state reporting endpoint speaks SOAP, and it is not going to change. Your new code runs on .NET 8, where Add Service Reference and the System.ServiceModel you knew from .NET Framework are not built in.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

The generated WCF client implements IDisposable, and its Dispose calls Close. If the call faulted, the channel is in the Faulted state, Close throws a CommunicationObjectFaultedException, and that exception replaces the original one. Your log says "the communication object cannot be used because it is in the Faulted state" and the real cause, perhaps a SOAP fault saying the currency code is invalid, is lost. On .NET Framework the endpoint, binding and timeouts also lived in a long <system.serviceModel> section in web.config.

Requirements: Python 3.12+. Install: pip install zeep · Needs at run time: the SOAP/WCF service it calls. The module loads without them; calling the code does not work without them.

Python Call a SOAP service inside a with-block whose close hides the real error (p288_r13_4_wcf_client_using_dispose_before.py)
"""Call a SOAP service inside a with-block whose close hides the real error

Source: ImproveCode, Chapter 13, Recipe 13.4 "Calling Legacy SOAP and WCF Services"
Section: The way it's often written
Book page: 288-289  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The generated WCF proxy -> a zeep-based proxy whose __exit__ calls close(); like WCF's
Dispose, close() raises on a faulted channel, so the exception from __exit__ replaces
the original call failure.
"""

from __future__ import annotations

from decimal import Decimal
from types import TracebackType

import zeep


class CommunicationObjectFaultedError(Exception):
    pass


class RateServiceClient:
    """Stand-in for the svcutil-generated proxy, backed by zeep."""

    WSDL = "https://rates.example.com/RateService.svc?wsdl"

    def __init__(self) -> None:
        self._client = zeep.Client(self.WSDL)
        self._faulted = False

    def get_rate(self, from_currency: str, to_currency: str) -> Decimal:
        try:
            return Decimal(str(self._client.service.GetRate(
                fromCurrency=from_currency, toCurrency=to_currency)))
        except Exception:
            self._faulted = True
            raise

    def close(self) -> None:
        if self._faulted:
            raise CommunicationObjectFaultedError(
                "The communication object cannot be used because it is in the Faulted state.")
        self._client.transport.session.close()

    def __enter__(self) -> RateServiceClient:
        return self

    def __exit__(
            self,
            exc_type: type[BaseException] | None,
            exc: BaseException | None,
            tb: TracebackType | None) -> None:
        self.close()  # Dispose == Close: throws again on a faulted channel


# Not to copy: Dispose throws on a faulted channel and hides the error
def get_usd_eur_rate() -> Decimal:
    with RateServiceClient() as client:
        return client.get_rate("USD", "EUR")

The improved recipe

The WCF client libraries are available for modern .NET as NuGet packages: System.ServiceModel.Http for HTTP bindings and System.ServiceModel.Primitives for the core types. Generate a proxy with dotnet-svcutil, or for a small service write the contract by hand, and manage the channel with a helper that closes on success and aborts on failure.

To generate a client from the service's WSDL:

PowerShell
dotnet tool install --global dotnet-svcutil
dotnet-svcutil https://legacy.example.com/RateService.svc?wsdl `
    --namespace "*,ImproveCode.Legacy.Rates" `
    --outputDir Connected/RateService

For a service with a handful of operations, a hand-written contract is shorter and easier to read than the generated file:

Register the gateway as a singleton, with the endpoint and credentials from configuration:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Run one call on a channel: close on success, abort on failure (p289_r13_4_channel_close_or_abort_call.py)
"""Run one call on a channel: close on success, abort on failure

Source: ImproveCode, Chapter 13, Recipe 13.4 "Calling Legacy SOAP and WCF Services"
Section: The improved recipe
Book page: 289-290  -- original C# listing
Converted from C# to Python.
ChannelFactory<T>/ICommunicationObject -> Protocols; the extension method becomes a
generic async function. close()/abort() are async here because Python SOAP clients
(zeep over httpx) release their resources asynchronously.
"""

from __future__ import annotations

from collections.abc import Awaitable, Callable
from typing import Protocol, cast


class CommunicationObject(Protocol):
    async def close(self) -> None: ...
    async def abort(self) -> None: ...


class ChannelFactory[TChannel](Protocol):
    def create_channel(self) -> TChannel: ...


async def call_async[TChannel, TResult](
        factory: ChannelFactory[TChannel],
        call: Callable[[TChannel], Awaitable[TResult]]) -> TResult:
    """Opens a channel, runs one call, closes it on
    success and aborts it on failure."""
    channel = factory.create_channel()
    communication = cast(CommunicationObject, channel)
    closed = False
    try:
        result = await call(channel)
        await communication.close()
        closed = True
        return result
    finally:
        if not closed:
            await communication.abort()

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Async service contract for the legacy rate service (p289_r13_4_rate_service_contract.py)
"""Async service contract for the legacy rate service

Source: ImproveCode, Chapter 13, Recipe 13.4 "Calling Legacy SOAP and WCF Services"
Section: The improved recipe
Book page: 289  -- original C# listing
Converted from C# to Python.
[ServiceContract]/[OperationContract] interface -> typing.Protocol; the contract
namespace is kept as a constant because zeep resolves operations from the WSDL.
"""

from __future__ import annotations

from decimal import Decimal
from typing import Protocol

RATE_SERVICE_NAMESPACE = "http://example.com/rates/2006"


class IRateService(Protocol):
    async def get_rate(self, from_currency: str, to_currency: str) -> Decimal: ...

Requirements: Python 3.12+. Install: pip install httpx zeep · Needs at run time: the SOAP/WCF service it calls. The module loads without them; calling the code does not work without them.

Python Rate service gateway: HTTPS basic auth, timeouts and safe channel handling (p290_r13_4_rate_service_gateway.py)
"""Rate service gateway: HTTPS basic auth, timeouts and safe channel handling

Source: ImproveCode, Chapter 13, Recipe 13.4 "Calling Legacy SOAP and WCF Services"
Section: The improved recipe
Book page: 290-291  -- original C# listing
Converted from C# to Python.
BasicHttpsBinding + ChannelFactory -> zeep.AsyncClient over a shared httpx.AsyncClient
(httpx.BasicAuth, httpx.Timeout for open/send/receive, a response hook enforcing
MaxReceivedMessageSize); IDisposable -> async context manager. httpx has no Faulted
state, so Close and Abort of the factory both reduce to closing the connection pool.
"""

from __future__ import annotations

from decimal import Decimal
from types import TracebackType

import httpx
import zeep
from zeep.transports import AsyncTransport

from p289_r13_4_channel_close_or_abort_call import call_async

MAX_RECEIVED_MESSAGE_SIZE = 4 * 1024 * 1024


async def _check_message_size(response: httpx.Response) -> None:
    length = int(response.headers.get("content-length", "0"))
    if length > MAX_RECEIVED_MESSAGE_SIZE:
        raise httpx.HTTPError(
            f"Response of {length} bytes exceeds MaxReceivedMessageSize.")


class _RateChannel:
    """One per call, like a WCF channel; implements IRateService."""

    def __init__(self, service: zeep.proxy.AsyncServiceProxy) -> None:
        self._service = service
        self._open = True

    async def get_rate(self, from_currency: str, to_currency: str) -> Decimal:
        result = await self._service.GetRate(
            fromCurrency=from_currency, toCurrency=to_currency)
        return Decimal(str(result))

    async def close(self) -> None:
        self._open = False

    async def abort(self) -> None:
        # Nothing to flush; the shared pool drops broken connections itself.
        self._open = False


class _RateChannelFactory:
    def __init__(self, endpoint: str, user_name: str, password: str) -> None:
        self._endpoint = endpoint
        auth = httpx.BasicAuth(user_name, password)
        self._http = httpx.AsyncClient(
            auth=auth,
            timeout=httpx.Timeout(30.0, connect=10.0),  # Send/Receive 30s, Open 10s
            event_hooks={"response": [_check_message_size]})
        self._wsdl_http = httpx.Client(auth=auth, timeout=10.0)
        self._client = zeep.AsyncClient(
            f"{endpoint}?wsdl",
            transport=AsyncTransport(client=self._http, wsdl_client=self._wsdl_http))
        self._binding = next(iter(self._client.wsdl.bindings))

    def create_channel(self) -> _RateChannel:
        return _RateChannel(
            self._client.create_service(self._binding, self._endpoint))

    async def aclose(self) -> None:
        await self._http.aclose()
        self._wsdl_http.close()


class RateServiceGateway:
    def __init__(self, endpoint: str, user_name: str, password: str) -> None:
        if not endpoint.lower().startswith("https://"):
            raise ValueError("BasicHttpsSecurityMode.Transport requires an https endpoint.")
        self._factory = _RateChannelFactory(endpoint, user_name, password)

    async def get_rate(self, from_: str, to: str) -> Decimal:
        # Cancellation: cancel the awaiting task (the WaitAsync(ct) equivalent).
        return await call_async(
            self._factory, lambda channel: channel.get_rate(from_, to))

    async def aclose(self) -> None:
        await self._factory.aclose()

    async def __aenter__(self) -> RateServiceGateway:
        return self

    async def __aexit__(
            self,
            exc_type: type[BaseException] | None,
            exc: BaseException | None,
            tb: TracebackType | None) -> None:
        await self.aclose()

Requirements: Python 3.12+. Install: pip install fastapi

Python Register the rate service gateway as an application singleton (p291_r13_4_register_rate_gateway_singleton.py)
"""Register the rate service gateway as an application singleton

Source: ImproveCode, Chapter 13, Recipe 13.4 "Calling Legacy SOAP and WCF Services"
Section: The improved recipe
Book page: 291  -- original C# listing
Converted from C# to Python.
builder.Services.AddSingleton -> a FastAPI lifespan that creates one gateway from
configuration (os.environ, keys Rates__Endpoint etc.) and disposes it at shutdown.
"""

from __future__ import annotations

import os
from collections.abc import AsyncIterator
from contextlib import asynccontextmanager

from fastapi import FastAPI

from p290_r13_4_rate_service_gateway import RateServiceGateway


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    async with RateServiceGateway(
            os.environ["Rates__Endpoint"],
            os.environ["Rates__UserName"],
            os.environ["Rates__Password"]) as gateway:
        app.state.rate_gateway = gateway
        yield


app = FastAPI(lifespan=lifespan)

How it works

dotnet-svcutil is the modern replacement for Add Service Reference. It reads the WSDL, writes a C# file with the data contracts, a service contract interface and a client class, and adds the System.ServiceModel.* package references. The generated operations are asynchronous by default. The generated client is a partial class with a ConfigureEndpoint partial method, so you can set timeouts and credentials in your own file and regenerate without losing them.

The hand-written contract shows how little is really needed. The Namespace on [ServiceContract] must match the service's target namespace from the WSDL, and the operation and parameter names must match the message parts. Get either wrong and the server replies with a fault about an unrecognized action, or the parameters arrive empty.

ChannelFactory<T> is expensive to create and thread-safe once opened, so the gateway builds one and keeps it. Channels are cheap. CallAsync creates one per call, runs the operation, and then either closes it cleanly or aborts it. Abort never throws, so the original exception, whether a FaultException, a TimeoutException or a CommunicationException, is the one that reaches your log.

The binding replaces the old web.config section. Every value that used to live in XML is now a property you can see, review and bind from configuration. MaxReceivedMessageSize matters more than any other: the default is 64 KB, and the first large response fails with a quota error.

Variations and pitfalls

  • Match the package version to your runtime. The System.ServiceModel.* packages version along with .NET. Version 8.1.2 works on .NET 8 and .NET 9; newer major versions may require a newer target framework.
  • What the client packages support. HTTP and HTTPS bindings, NetTcpBinding (with the System.ServiceModel.NetTcp package), transport security and basic, Windows or certificate credentials. Full message-level WSHttpBinding security and some WS-* features are limited or missing. Check before you promise a migration date.
  • Cancellation. WCF operations don't take a CancellationToken. WaitAsync(ct) stops your code from waiting, but the call keeps running until SendTimeout. Keep that timeout realistic.
  • Hosting a WCF service on modern .NET. The client packages only call services. To host one, use CoreWCF, the community port supported by Microsoft, which lets existing SOAP clients keep working while the server moves to ASP.NET Core.
  • Tiny services. For one operation with a simple envelope, posting the SOAP XML with HttpClient and reading the result with LINQ to XML (Chapter 12) is a valid choice. It also gets you the factory and the resilience handler.
  • Secrets. The service password belongs in a secret store, not in appsettings.json. See Chapter 6.

On .NET Framework

The CallAsync helper works on .NET Framework with the built-in System.ServiceModel. It is worth adding to old projects on its own, because it fixes the hidden-exception problem without touching the generated proxies.