Covers implementing an anti-corruption layer in .NET: a domain-owned port, adapter and translator in infrastructure, a typed HttpClient facade, resilience, error translation and contract tests.
An anti-corruption layer is code on the downstream side that translates an upstream model into yours, so the upstream's names, codes and quirks never reach your domain. It has three parts. A port: an interface your domain defines in its own language (IIdentityVerifier). A facade/client: a typed HttpClient with AddStandardResilienceHandler() (timeouts, retries with jitter, circuit breaker). A translator: pure functions mapping both ways, vendor DTOs and codes to your value objects and your types to validated vendor requests. An adapter implements the port, lives in Infrastructure and is internal.
Unknown codes map to a safe outcome and are logged and metered so upstream changes are caught the same day. Test translators with unit tests, the adapter against WireMock.Net, and run contract tests against the sandbox. The trade-off: extra code, in exchange for surviving or replacing the upstream without touching the domain.
"I build an anti-corruption layer whenever my core domain depends on a model I can't control and don't want to adopt: a legacy mainframe, a SOAP service with cryptic codes, or a vendor API. The goal is that the upstream's language stops at one boundary. My domain never sees
VRF_STS_CD = 'P2'; it seesVerificationOutcome.NeedsManualReview.Structurally there are three pieces. First, the port, an interface owned by the domain or application layer and written in our language, like
IIdentityVerifier.VerifyAsync(Applicant, ct)returning our own result type. Second, the facade or client, which is a typedHttpClientthat knows the upstream's URLs, auth and DTOs, with the standard resilience handler for retries, timeouts and a circuit breaker. Third, the translator, a static class of pure functions that maps their DTOs and codes into our value objects. An adapter class implements the port by calling the client and then the translator. All of that sits in an Infrastructure folder for that integration, markedinternal, and only the DI registration is public.Two details matter in practice. One is unknown values: when the vendor adds a new status code, the translator must not quietly default to 'approved'. I map unknown codes to an explicit failure, log it with the raw value, and increment a metric so we find out the same day. The other is errors: their HTTP 500s and SOAP faults become our domain-level outcomes or a single infrastructure exception type, never their exception classes leaking upwards. For testing, the translator gets fast table-driven unit tests, the adapter gets tests against WireMock.Net with recorded responses, and a nightly contract test hits the vendor's sandbox. The mistake I see is the ACL being a thin pass-through that just renames the class but still returns the vendor's fields; then it isn't protecting anything."
| Part | Knows about | Project / folder | Visibility |
|---|---|---|---|
| Port (interface) | Domain types only | Domain or Application | public |
| Facade / client | Upstream protocol, auth, DTOs | Infrastructure/Integrations/Vendor | internal |
| Translator | Upstream DTOs + domain types | Infrastructure/Integrations/Vendor | internal |
| Adapter | Port, client, translator | Infrastructure/Integrations/Vendor | internal |
| DI registration | Everything above | Infrastructure (extension method) | public |
| Test | Tool | Catches |
|---|---|---|
| Translator unit tests | xUnit theory with every code | Mapping mistakes, unknown codes |
| Adapter tests | WireMock.Net with recorded JSON | Serialisation, headers, error handling |
| Contract test | Vendor sandbox, nightly | Upstream changes before production |
| Domain tests | Fake implementation of the port | Domain logic, no network |
We wrapped a [document-verification vendor] used for Australian identity checks (driver licence and passport via the [DVS] gateway) behind an IIdentityVerifier ACL. When we moved to a [second vendor] [18 months] later, the change was a new adapter of [about 350 lines] plus its tests; the onboarding domain and its [120] tests didn't change, and the cut-over was a feature flag.
Checks that the candidate can implement an ACL that actually translates a model, places it correctly, and makes it resilient and testable.
Green flags
HttpClient with the standard resilience handlerRed flags
Wrapping hides the transport; translation hides the model. If your interface returns VendorResultDto, you have an adapter but not an ACL. The ACL's job is semantic: mapping concepts, codes, units, time zones and identities.
Onboarding domain ACL (Infrastructure) Vendor
----------------- -------------------- ------
IIdentityVerifier ◄── VendorIdentityAdapter ──► VendorClient ── HTTPS ──► /v3/checks
Applicant │ (typed HttpClient,
VerificationOutcome ▼ resilience, auth)
VendorTranslator
(DTO ↔ domain, codes, dates, errors)
| Concern | Example |
|---|---|
| Codes | "P2" → NeedsManualReview |
| Units | cents → Money in dollars |
| Time | "20261120" in AEST → DateOnly / DateTimeOffset |
| Identity | vendor reference → your VerificationId |
| Structure | flat 60-field record → small value objects |
| Errors | {"err":"E104"} → VerificationOutcome.DocumentExpired |
AddHttpClient<VendorClient>().AddStandardResilienceHandler() (Microsoft.Extensions.Http.Resilience, built on Polly v8) adds a total timeout, retry with exponential backoff and jitter, a circuit breaker and an attempt timeout. Only retry idempotent calls or calls with an idempotency key.
When you also send data upstream (create a policy in the legacy system), the translator maps both ways. Keep the outbound mapping just as strict: validate before sending.
Log upstream request ids and raw codes on translation failures (never PII: identity documents fall under the Privacy Act 1988 and APPs). Emit a counter like acl.translation_failures{vendor,code} and alert on any non-zero rate after a vendor release.
AddStandardResilienceHandler() and simulate a 503 burst; watch retries in logs.An identity-verification ACL: port, client, translator, adapter, DI and tests.
// Domain (or Application): the port, in our language.
namespace Onboarding.Domain;
public sealed record Applicant(string GivenName, string FamilyName, DateOnly DateOfBirth, string LicenceNumber, string State);
public enum VerificationOutcome { Verified, NotVerified, NeedsManualReview, DocumentExpired, Unavailable }
public interface IIdentityVerifier
{
Task<VerificationOutcome> VerifyAsync(Applicant applicant, CancellationToken ct);
}
// Infrastructure: the ACL. Everything internal except registration.
namespace Onboarding.Infrastructure.IdVendor;
using System.Net.Http.Json;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Onboarding.Domain;
internal sealed record VendorCheckRequest(string fn, string ln, string dob, string doc_no, string doc_juris);
internal sealed record VendorCheckResponse(string ref_id, string sts_cd, string? err);
internal sealed class VendorClient(HttpClient http)
{
public async Task<VendorCheckResponse?> CheckAsync(VendorCheckRequest req, CancellationToken ct)
{
using var resp = await http.PostAsJsonAsync("/v3/checks", req, ct);
resp.EnsureSuccessStatusCode();
return await resp.Content.ReadFromJsonAsync<VendorCheckResponse>(ct);
}
}
internal static class VendorTranslator
{
public static VendorCheckRequest ToVendor(Applicant a) =>
new(a.GivenName, a.FamilyName, a.DateOfBirth.ToString("yyyyMMdd"), a.LicenceNumber, a.State);
public static VerificationOutcome? ToDomain(VendorCheckResponse r) => (r.sts_cd, r.err) switch
{
("Y", _) => VerificationOutcome.Verified,
("N", _) => VerificationOutcome.NotVerified,
("P1" or "P2", _) => VerificationOutcome.NeedsManualReview,
(_, "E104") => VerificationOutcome.DocumentExpired,
_ => null // unknown: caller decides; never silently 'Verified'
};
}
internal sealed class VendorIdentityAdapter(VendorClient client, ILogger<VendorIdentityAdapter> log) : IIdentityVerifier
{
public async Task<VerificationOutcome> VerifyAsync(Applicant applicant, CancellationToken ct)
{
try
{
var resp = await client.CheckAsync(VendorTranslator.ToVendor(applicant), ct);
if (resp is null) return VerificationOutcome.Unavailable;
var outcome = VendorTranslator.ToDomain(resp);
if (outcome is null)
{
log.LogWarning("Unknown vendor status {Status}/{Error} for ref {Ref}", resp.sts_cd, resp.err, resp.ref_id);
return VerificationOutcome.NeedsManualReview; // safe default for an unknown code
}
return outcome.Value;
}
catch (HttpRequestException ex)
{
log.LogError(ex, "Identity vendor unavailable");
return VerificationOutcome.Unavailable; // vendor exceptions never leak upwards
}
}
}
public static class IdVendorRegistration
{
public static IServiceCollection AddIdVendor(this IServiceCollection services, Uri baseAddress)
{
services.AddHttpClient<VendorClient>(c => c.BaseAddress = baseAddress)
.AddStandardResilienceHandler();
services.AddScoped<IIdentityVerifier, VendorIdentityAdapter>();
return services;
}
}
// Tests: translator is pure, so tests are trivial and fast.
public class VendorTranslatorTests
{
[Theory]
[InlineData("Y", null, VerificationOutcome.Verified)]
[InlineData("N", null, VerificationOutcome.NotVerified)]
[InlineData("P2", null, VerificationOutcome.NeedsManualReview)]
[InlineData("X", "E104", VerificationOutcome.DocumentExpired)]
public void Maps_known_codes(string sts, string? err, VerificationOutcome expected) =>
Assert.Equal(expected, VendorTranslator.ToDomain(new("r1", sts, err)));
[Fact]
public void Unknown_code_is_not_silently_accepted() =>
Assert.Null(VendorTranslator.ToDomain(new("r1", "Z9", null)));
}
(InternalsVisibleTo lets the test project see the internal translator.)
internal types and a public DI extension method.An ACL is insurance: you pay a premium (translation code and tests) to protect the most valuable part of your system from things you don't control. It is worth it for a core domain and for any vendor you might replace; it is overkill for a supporting context reading a good upstream model, where conforming is cheaper.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Full ACL (port, client, translator) | Core domain, poor or volatile upstream, possible vendor swap | 300-800 lines per integration plus tests | Supporting context with a decent upstream |
| Thin adapter (conformist) | Supporting context, good upstream model | Low | Upstream naming would spread into a core model |
| Shared ACL service | Several contexts consuming the same legacy system | A service to run | Only one consumer |
I measure the ACL by translation failure counts after upstream releases and by how much domain code changes when the vendor changes (target: none).
Adapter converts the interface of an existing class into the interface your code expects, without changing either side. It's a translator.
For a payment SDK, I define IPaymentGateway in my domain's terms. A StripePaymentGateway adapter then turns it into SDK calls, translating types and units (decimal AUD to cents), statuses and vendor exceptions into domain results. That keeps vendor types out of the codebase, lets tests use a fake, and confines a provider change to one class.
The trade-off is an extra layer. Keep it thin: an adapter translates, and business rules don't belong in it.
They are variations of one idea: put the domain at the centre and make every source dependency point inwards, so technology plugs into the business logic rather than the reverse.
The trade-off is the same for all three: testable, swappable boundaries in exchange for more interfaces and indirection.
A context map shows the bounded contexts and how their teams and models relate. Each relationship has an upstream (whose model influences others) and a downstream. The patterns describe who adapts: partnership (teams succeed or fail together), shared kernel (a small model both own), customer-supplier (upstream plans for downstream needs), conformist (downstream simply adopts the upstream model), anti-corruption layer (downstream translates to protect its model), open host service with a published language (upstream offers a stable, versioned protocol for many consumers) and separate ways (do not integrate).
I choose by power (can I influence the upstream?), upstream model quality, how core my context is and how many consumers exist. The trade-off is translation cost versus model purity: an ACL costs code, conforming costs your model.
How to tell it (STAR)
**S:** At [company], a vendor added a new status code and our onboarding flow auto-approved [40+] applications without a full identity check. **T:** I [led the incident fix and the follow-up design]. **A:** I paused auto-approval behind a flag within [an hour], then replaced the leaky integration with an anti-corruption layer whose translator treats unknown codes as manual review, added an alert on unknown codes and a nightly contract test. **R:** No unverified approvals since; the next two vendor code changes were caught by the alert [the same day], and a later vendor switch changed one adapter and no domain code.
Last updated 23 Nov 2026.