Adapter intent, object vs class adapter, wrapping a vendor SDK (Stripe.net) behind a domain interface, translating units, types and exceptions, .NET examples (StreamReader, TaskCompletionSource, Serilog's ILoggerProvider), and keeping business logic out of adapters.
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.
"Adapter is a translator between two interfaces that don't match. My code expects one shape, the target. An existing class, the adaptee, offers another. The adapter implements the target and calls the adaptee, so neither has to change. In C# it's almost always an object adapter: the adapter holds the adaptee in a field and delegates. A class adapter inherits from the adaptee and implements the target, but with single inheritance and sealed SDK types it's rarely possible or wise.
A payment SDK is the classic case. I don't want Stripe's types all over my code, so I define
IPaymentGatewayin my own terms, something likeChargeAsync(Money amount, PaymentMethodToken token, CancellationToken ct)returning aPaymentResult. ThenStripePaymentGatewayimplements it with the SDK'sPaymentIntentService. The adapter's job is translation. Stripe wants amounts as alongin cents and a lowercase currency code, so$12.34 AUDbecomes1234and"aud". It maps Stripe's statuses to my result type, and it catchesStripeExceptionand turns card declines into a domain result rather than letting a vendor exception leak out. The rest of the system only knowsIPaymentGateway, so tests use a fake and adding a second provider is one new class. You see the same idea in the framework:StreamReaderadapts a byteStreaminto aTextReader,TaskCompletionSourceadapts callback APIs intoTasks, and Serilog's provider adapts Serilog intoILogger.The mistake I see is the adapter slowly gaining business logic, like retries, fraud rules or discounts, until it's the most important class in the system and tied to one vendor. An adapter should translate, not decide."
| Role | In the payment example |
|---|---|
| Target | IPaymentGateway (your interface) |
| Adaptee | Stripe.net PaymentIntentService |
| Adapter | StripePaymentGateway |
| Client | CheckoutService |
| Object adapter | Class adapter | |
|---|---|---|
| Mechanism | Composition (field) | Inheritance |
| Works with sealed adaptee | Yes | No |
| Adapts subclasses of the adaptee | Yes | No |
| Can override adaptee behaviour | No | Yes |
| Typical in C# | Yes | Rare |
| Belongs inside | Belongs elsewhere |
|---|---|
| Unit and type conversion (decimal β cents) | Pricing, discounts, tax |
| Mapping vendor statuses and errors | Fraud and business rules |
| Vendor authentication headers | Retry and circuit breaker (resilience pipeline or decorator) |
| Vendor DTOs | Domain entities |
A retailer had Stripe types such as PaymentIntent and StripeException referenced in 60 files. When they added a bank-transfer option, the change touched most of those files and took three sprints. After moving everything behind an IPaymentGateway adapter, adding a second provider later took about four days and touched one project.
Checks whether the candidate can isolate external dependencies cleanly and knows what an adapter should and shouldn't do.
Green flags
Red flags
Client βββΆ Β«interfaceΒ» Target Adaptee
+ Request() + SpecificRequest()
β² β²
β implements β holds (composition)
Adapter ββββββββββββββββββββββββββ
Request() => adaptee.SpecificRequest(translate(args))
This is the Dependency Inversion Principle in action: the domain owns the abstraction (IPaymentGateway), and the infrastructure (the adapter) depends on it. The interface describes what your system needs, not what the vendor offers, so it is usually smaller than the SDK and named in domain language.
| Concern | Example |
|---|---|
| Units | AUD dollars (decimal) β cents (long); timestamps from Unix seconds β DateTimeOffset |
| Identifiers | Your OrderId β vendor metadata or idempotency key |
| Errors | StripeException with card_declined β PaymentResult.Declined; network error β rethrow for resilience to handle |
| Async models | Callback/event API β Task via TaskCompletionSource<T> |
| Paging | Vendor cursor pages β IAsyncEnumerable<T> |
StreamReader/StreamWriter: byte stream β text reader/writer (with decoding).TaskCompletionSource<T>: any completion signal β Task<T>; Task.Factory.FromAsync adapts the old Begin/End (APM) pattern.Serilog.Extensions.Logging: Serilog ILogger β Microsoft ILoggerProvider.ReadOnlyCollection<T>: IList<T> β read-only view.When a whole external model (an ERP, a legacy system) doesn't fit your domain, a set of adapters plus translators forms an anti-corruption layer (DDD). Same idea, bigger scope.
System.Timers.Timer's Elapsed event in a method returning Task using TaskCompletionSource.IPaymentGateway and a fake; write a CheckoutService test that never references a vendor type.using Stripe;) outside the infrastructure project.A thin object adapter over Stripe.net that translates units, statuses and exceptions:
namespace Payments;
using Stripe;
public sealed record Money(decimal Amount, string Currency);
public sealed record PaymentResult(bool Succeeded, string? Reference, string? DeclineReason);
public interface IPaymentGateway // owned by the domain, in domain language
{
Task<PaymentResult> ChargeAsync(Guid orderId, Money amount, string paymentMethodToken, CancellationToken ct);
}
public sealed class StripePaymentGateway(PaymentIntentService intents) : IPaymentGateway
{
public async Task<PaymentResult> ChargeAsync(Guid orderId, Money amount, string paymentMethodToken, CancellationToken ct)
{
var options = new PaymentIntentCreateOptions
{
Amount = (long)decimal.Round(amount.Amount * 100m, MidpointRounding.AwayFromZero), // AUD dollars -> cents
Currency = amount.Currency.ToLowerInvariant(), // "AUD" -> "aud"
PaymentMethod = paymentMethodToken,
Confirm = true,
};
var request = new RequestOptions { IdempotencyKey = orderId.ToString() }; // safe to retry
try
{
PaymentIntent pi = await intents.CreateAsync(options, request, ct);
return pi.Status == "succeeded"
? new PaymentResult(true, pi.Id, null)
: new PaymentResult(false, pi.Id, pi.Status);
}
catch (StripeException ex) when (ex.StripeError?.Type == "card_error")
{
return new PaymentResult(false, null, ex.StripeError.DeclineCode ?? ex.StripeError.Code); // a decline is a result, not a crash
}
// Other StripeExceptions (network, 5xx) propagate so the resilience pipeline can handle them
}
}
// Program.cs
// builder.Services.AddSingleton(new StripeClient(builder.Configuration["Stripe:SecretKey"]));
// builder.Services.AddSingleton(sp => new PaymentIntentService(sp.GetRequiredService<StripeClient>()));
// builder.Services.AddScoped<IPaymentGateway, StripePaymentGateway>();
PaymentIntent, StripeException) appear in controllers and domain code. Why it is wrong: Every vendor change ripples through the system and tests need the SDK. Instead: Keep vendor types inside the adapter and expose domain types.Adapters are cheap insurance at system boundaries: payment providers, email and SMS services, identity providers, legacy systems. The value is containment: vendor churn, SDK upgrades and licensing changes stay inside one class. The risk is an adapter that grows into a hidden domain layer.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Use the SDK directly | Prototype, a single small call site | Vendor types spread | Core business flows |
| Thin adapter behind a domain interface | Any external dependency on a core path | One interface + class | Code you own |
| Anti-corruption layer | A large external model that conflicts with yours | Translators, mapping tests | A single simple API |
I check adapter health with an architecture test (domain can't reference the vendor namespace) and by counting where vendor types appear.
This is a Strategy (IPaymentGateway) chosen by a factory. There are three DI-friendly ways to do it:
AddKeyedScoped<IPaymentGateway, StripeGateway>("stripe"), then inject with [FromKeyedServices("stripe")]. This only works when the key is known at compile time.IEnumerable<IPaymentGateway> resolver: each gateway exposes a Provider key, and a resolver builds a FrozenDictionary from them. There's no container access, but every gateway is constructed.IPaymentGatewayResolver.Resolve(provider) calls GetRequiredKeyedService inside the composition root. It builds only the gateway you need.To avoid a service locator, business code depends on a narrow typed resolver, never on IServiceProvider. Map unknown keys to a domain error, and validate the configured keys at startup.
ISP says clients should not be forced to depend on methods they do not use. A fat interface such as IOrderService with 25 members couples every consumer to all of them, makes test doubles painful and pushes implementers to throw NotImplementedException. Split interfaces by what clients need (role interfaces): IOrderReader for queries, IOrderWriter for commands, IClock instead of a giant IUtilities. The BCL does this well (IReadOnlyCollection<T> versus ICollection<T>, IAsyncDisposable). Do not go to the extreme of one interface per method; group members that the same client uses together.
Last updated 18 Nov 2026.