
Teníamos un dominio limpio. Orders, customers, payments — todo modelado con cuidado, todo hablando el mismo lenguaje. Entonces integramos un proveedor de pagos.
Seis meses después, el enum PaymentStatus tenía valores como PSPCONFIRMED, PSPREJECTED_RETRY y AUTHORISED_3DS. Nuestra entidad Order tenía un campo StripeChargeId. Nuestra capa de servicio llamaba a MapFromStripeWebhookPayload(). Y cada desarrollador que tocaba pagos tenía que entender el modelo de objetos de Stripe antes de poder entender el nuestro.
El dominio no había cambiado. Pero se había contaminado.
El Anti-Corruption Layer es el patrón que evita esto. Así es como funciona y cómo implementarlo en .NET.
Qué es el Anti-Corruption Layer
El término viene de Domain-Driven Design, de Eric Evans. Cuando dos sistemas necesitan comunicarse, el límite entre ellos es peligroso. El sistema externo tiene su propio modelo, su propio vocabulario, sus propias suposiciones sobre el mundo — y si dejas que esos conceptos se filtren en tu dominio, terminas modelando su mundo en lugar del tuyo.
El Anti-Corruption Layer (ACL) es una frontera de traducción. Se sitúa entre tu dominio y el sistema externo, convirtiendo el modelo externo en tu modelo de dominio — y viceversa. Tu dominio nunca ve los tipos externos. El sistema externo nunca ve los tipos de tu dominio.

No es solo un mapper. Es una frontera arquitectónica que dice: todo en este lado habla nuestro idioma, todo en ese lado habla el suyo, y esta capa traduce entre los dos.
La diferencia entre el ACL y el Adapter Pattern
Ya conoces el Adapter Pattern — envuelve una interfaz incompatible para hacerla compatible. El ACL hace algo más profundo: traduce entre dos modelos conceptuales distintos, no solo entre dos interfaces distintas.
Un Adapter cambia la forma de una llamada. Un ACL cambia el significado.
| Adapter Pattern | Anti-Corruption Layer | |
|---|---|---|
| Propósito | Compatibilidad de interfaces | Traducción de modelo conceptual |
| Opera en | Nivel de infraestructura | Frontera de dominio |
| Gestiona | Firmas de métodos | Conceptos y lenguaje de dominio |
| Complejidad | Baja | Media-alta |
En la práctica, un ACL a menudo usa adapters internamente — pero su intención es la traducción de modelo, no la adaptación de interfaces.
El problema sin un ACL
Empecemos con la contaminación. Estás construyendo una plataforma de e-commerce e integrando un proveedor de pagos. Sin un ACL, esto es lo que pasa:
// ❌ Domain entity contaminated by external concepts
public class Order
{
public Guid Id { get; private set; }
public decimal Total { get; private set; }
// Stripe concepts leaking into the domain
public string? StripePaymentIntentId { get; set; }
public string? StripeCustomerId { get; set; }
public string? StripeStatus { get; set; } // "requires_payment_method", "succeeded", etc.
}
// ❌ Service layer that understands Stripe better than your own domain
public class OrderService
{
private readonly StripeClient _stripe;
public async Task ProcessPaymentAsync(Guid orderId, string paymentMethodId)
{
var order = await _repository.GetByIdAsync(orderId);
// Stripe-specific logic inside domain service
var paymentIntent = await _stripe.PaymentIntents.CreateAsync(new PaymentIntentCreateOptions
{
Amount = (long)(order.Total * 100), // Stripe uses cents
Currency = "gbp",
PaymentMethod = paymentMethodId,
Confirm = true,
});
// Mapping Stripe statuses directly in domain logic
order.StripePaymentIntentId = paymentIntent.Id;
order.StripeStatus = paymentIntent.Status;
if (paymentIntent.Status == "succeeded")
order.MarkAsPaid();
else if (paymentIntent.Status == "requires_action")
order.MarkAsAwaitingAction();
}
}
Los problemas:
- Tu dominio sabe qué es un
PaymentIntent. No debería. - Cada desarrollador necesita conocer los strings de estado de Stripe para entender tu lógica de orders.
- Si cambias de proveedor de pagos, reescribes el dominio.
- Si Stripe renombra un estado, tienes que rastrear el código de dominio buscando las referencias.
Construyendo el Anti-Corruption Layer
El ACL tiene tres responsabilidades:
- Traducir modelos externos a modelos de dominio
- Aislar el código de dominio de los contratos de la API externa
- Absorber los cambios — cuando la API externa cambia, solo cambia el ACL
Paso 1: define tu modelo de dominio
Primero, define lo que tu dominio necesita, en tu propio lenguaje:
// Your domain concepts — no external dependencies
public record Payment
{
public PaymentId Id { get; init; }
public Money Amount { get; init; }
public PaymentStatus Status { get; init; }
public PaymentProvider Provider { get; init; }
public string ExternalReference { get; init; } = string.Empty;
public DateTimeOffset ProcessedAt { get; init; }
}
public enum PaymentStatus
{
Pending,
Authorised,
Captured,
Declined,
RequiresAction,
Refunded
}
public enum PaymentProvider
{
Stripe,
PayPal
}
public record Money(decimal Amount, string Currency)
{
public static Money GBP(decimal amount) => new(amount, "GBP");
public static Money USD(decimal amount) => new(amount, "USD");
}
public record PaymentId(string Value)
{
public static PaymentId New() => new(Guid.NewGuid().ToString());
}
Paso 2: define el puerto de dominio
El dominio declara lo que necesita a través de una interfaz — no le importa cómo se implementa:
// The domain's view of payment processing — no external types
public interface IPaymentGateway
{
Task<PaymentResult> ChargeAsync(PaymentRequest request, CancellationToken ct = default);
Task<PaymentResult> RefundAsync(string externalReference, Money amount, CancellationToken ct = default);
Task<Payment?> GetPaymentAsync(string externalReference, CancellationToken ct = default);
}
public record PaymentRequest(
Money Amount,
string PaymentMethodToken,
string OrderReference,
string CustomerEmail);
public record PaymentResult(
bool Success,
Payment? Payment,
string? ErrorMessage,
bool RequiresAction,
string? ActionUrl);
Paso 3: implementa el traductor del ACL
Este es el corazón del patrón. La implementación del ACL conoce Stripe — pero tu dominio nunca lo hará:
// Infrastructure layer — the only place that knows about Stripe
public class StripePaymentGateway : IPaymentGateway
{
private readonly PaymentIntentService _paymentIntentService;
private readonly RefundService _refundService;
private readonly ILogger<StripePaymentGateway> _logger;
public StripePaymentGateway(
PaymentIntentService paymentIntentService,
RefundService refundService,
ILogger<StripePaymentGateway> logger)
{
_paymentIntentService = paymentIntentService;
_refundService = refundService;
_logger = logger;
}
public async Task<PaymentResult> ChargeAsync(
PaymentRequest request,
CancellationToken ct = default)
{
try
{
// Translate domain request → Stripe request
var options = TranslateToStripeOptions(request);
var intent = await _paymentIntentService.CreateAsync(options, cancellationToken: ct);
// Translate Stripe response → domain Payment
var payment = TranslateFromStripe(intent);
var requiresAction = intent.Status == "requires_action";
return new PaymentResult(
Success: intent.Status is "succeeded" or "requires_action",
Payment: payment,
ErrorMessage: null,
RequiresAction: requiresAction,
ActionUrl: intent.NextAction?.RedirectToUrl?.Url);
}
catch (StripeException ex)
{
_logger.LogWarning(ex, "Stripe charge failed for order {OrderReference}", request.OrderReference);
// Translate Stripe error → domain result
return new PaymentResult(
Success: false,
Payment: null,
ErrorMessage: TranslateStripeError(ex.StripeError),
RequiresAction: false,
ActionUrl: null);
}
}
public async Task<PaymentResult> RefundAsync(
string externalReference,
Money amount,
CancellationToken ct = default)
{
try
{
var refund = await _refundService.CreateAsync(new RefundCreateOptions
{
PaymentIntent = externalReference,
Amount = ToStripeCents(amount),
}, cancellationToken: ct);
return new PaymentResult(
Success: refund.Status == "succeeded",
Payment: null,
ErrorMessage: null,
RequiresAction: false,
ActionUrl: null);
}
catch (StripeException ex)
{
_logger.LogError(ex, "Stripe refund failed for {ExternalReference}", externalReference);
return new PaymentResult(false, null, TranslateStripeError(ex.StripeError), false, null);
}
}
public async Task<Payment?> GetPaymentAsync(
string externalReference,
CancellationToken ct = default)
{
try
{
var intent = await _paymentIntentService.GetAsync(externalReference, cancellationToken: ct);
return TranslateFromStripe(intent);
}
catch (StripeException ex) when (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
{
return null;
}
}
// ── Translation methods ───────────────────────────────────────────────────
// These are the core of the ACL. All Stripe-specific knowledge lives here.
private static PaymentIntentCreateOptions TranslateToStripeOptions(PaymentRequest request) =>
new()
{
Amount = ToStripeCents(request.Amount),
Currency = request.Amount.Currency.ToLowerInvariant(),
PaymentMethod = request.PaymentMethodToken,
Confirm = true,
ReceiptEmail = request.CustomerEmail,
Metadata = new Dictionary<string, string>
{
["order_reference"] = request.OrderReference
}
};
private static Payment TranslateFromStripe(PaymentIntent intent) =>
new()
{
Id = new PaymentId(intent.Id),
Amount = new Money(intent.Amount / 100m, intent.Currency.ToUpperInvariant()),
Status = TranslateStripeStatus(intent.Status),
Provider = PaymentProvider.Stripe,
ExternalReference = intent.Id,
ProcessedAt = intent.Created
};
private static PaymentStatus TranslateStripeStatus(string stripeStatus) =>
stripeStatus switch
{
"requires_payment_method" => PaymentStatus.Pending,
"requires_confirmation" => PaymentStatus.Pending,
"requires_action" => PaymentStatus.RequiresAction,
"processing" => PaymentStatus.Pending,
"succeeded" => PaymentStatus.Captured,
"canceled" => PaymentStatus.Declined,
_ => PaymentStatus.Pending
};
private static string TranslateStripeError(StripeError? error) =>
error?.Code switch
{
"card_declined" => "Your card was declined.",
"insufficient_funds" => "Insufficient funds on your card.",
"incorrect_cvc" => "The security code is incorrect.",
"expired_card" => "Your card has expired.",
"processing_error" => "A processing error occurred. Please try again.",
_ => "Payment could not be processed. Please try again."
};
private static long ToStripeCents(Money money) => (long)(money.Amount * 100);
}
Paso 4: el servicio de dominio limpio
Ahora mira lo limpio que queda tu servicio de dominio:
// ✅ Domain service that knows nothing about Stripe
public class OrderPaymentService
{
private readonly IOrderRepository _orders;
private readonly IPaymentGateway _paymentGateway; // domain interface, not Stripe
private readonly ILogger<OrderPaymentService> _logger;
public OrderPaymentService(
IOrderRepository orders,
IPaymentGateway paymentGateway,
ILogger<OrderPaymentService> logger)
{
_orders = orders;
_paymentGateway = paymentGateway;
_logger = logger;
}
public async Task<PaymentOutcome> ProcessPaymentAsync(
Guid orderId,
string paymentMethodToken,
CancellationToken ct = default)
{
var order = await _orders.GetByIdAsync(orderId, ct)
?? throw new OrderNotFoundException(orderId);
var request = new PaymentRequest(
Amount: Money.GBP(order.Total),
PaymentMethodToken: paymentMethodToken,
OrderReference: order.Reference,
CustomerEmail: order.CustomerEmail);
var result = await _paymentGateway.ChargeAsync(request, ct);
if (!result.Success)
{
_logger.LogWarning("Payment failed for order {OrderId}: {Error}", orderId, result.ErrorMessage);
return PaymentOutcome.Failed(result.ErrorMessage!);
}
if (result.RequiresAction)
{
order.AwaitCustomerAction(result.Payment!);
await _orders.SaveAsync(order, ct);
return PaymentOutcome.RequiresAction(result.ActionUrl!);
}
order.MarkAsPaid(result.Payment!);
await _orders.SaveAsync(order, ct);
return PaymentOutcome.Succeeded(result.Payment!);
}
}
public record PaymentOutcome
{
public bool IsSuccess { get; init; }
public bool NeedsAction { get; init; }
public string? ActionUrl { get; init; }
public string? Error { get; init; }
public Payment? Payment { get; init; }
public static PaymentOutcome Succeeded(Payment payment) =>
new() { IsSuccess = true, Payment = payment };
public static PaymentOutcome RequiresAction(string actionUrl) =>
new() { IsSuccess = true, NeedsAction = true, ActionUrl = actionUrl };
public static PaymentOutcome Failed(string error) =>
new() { IsSuccess = false, Error = error };
}
Nada de PaymentIntent. Nada de StripeException. Nada de requires_payment_method. El servicio de dominio es legible por cualquiera que entienda el negocio, no solo por desarrolladores que conocen Stripe.
Paso 5: conectándolo
// Program.cs
builder.Services.AddScoped<IPaymentGateway, StripePaymentGateway>();
// If you want to swap providers without touching the domain:
// builder.Services.AddScoped<IPaymentGateway, PayPalPaymentGateway>();
builder.Services.AddScoped<OrderPaymentService>();
// Stripe SDK services
builder.Services.AddSingleton<PaymentIntentService>();
builder.Services.AddSingleton<RefundService>();
StripeConfiguration.ApiKey = builder.Configuration["Stripe:SecretKey"];
Gestionando webhooks a través del ACL
Los webhooks son donde la contaminación es más peligrosa — recibes un payload externo en crudo y tienes que decidir qué significa para tu dominio.
// ❌ Without ACL — Stripe webhook logic inside domain
[HttpPost("webhooks/stripe")]
public async Task<IActionResult> StripeWebhook()
{
var payload = await new StreamReader(Request.Body).ReadToEndAsync();
var stripeEvent = EventUtility.ConstructEvent(payload, Request.Headers["Stripe-Signature"], _secret);
if (stripeEvent.Type == "payment_intent.succeeded")
{
var intent = stripeEvent.Data.Object as PaymentIntent;
// Now you're writing domain logic inside a Stripe webhook handler
}
}
// ✅ With ACL — the domain sees a domain event
public interface IPaymentWebhookTranslator
{
Task<DomainPaymentEvent?> TranslateAsync(string payload, string signature, CancellationToken ct = default);
}
public record DomainPaymentEvent(
DomainPaymentEventType Type,
string ExternalReference,
Money? Amount);
public enum DomainPaymentEventType
{
PaymentSucceeded,
PaymentFailed,
PaymentRefunded,
DisputeOpened
}
// ACL implementation — knows about Stripe
public class StripeWebhookTranslator : IPaymentWebhookTranslator
{
private readonly string _webhookSecret;
public StripeWebhookTranslator(IConfiguration config)
{
_webhookSecret = config["Stripe:WebhookSecret"]!;
}
public Task<DomainPaymentEvent?> TranslateAsync(
string payload,
string signature,
CancellationToken ct = default)
{
Event stripeEvent;
try
{
stripeEvent = EventUtility.ConstructEvent(payload, signature, _webhookSecret);
}
catch (StripeException)
{
return Task.FromResult<DomainPaymentEvent?>(null);
}
var domainEvent = stripeEvent.Type switch
{
"payment_intent.succeeded" => TranslateSucceeded(stripeEvent),
"payment_intent.payment_failed" => TranslateFailed(stripeEvent),
"charge.refunded" => TranslateRefunded(stripeEvent),
"charge.dispute.created" => TranslateDispute(stripeEvent),
_ => null
};
return Task.FromResult(domainEvent);
}
private static DomainPaymentEvent? TranslateSucceeded(Event e)
{
if (e.Data.Object is not PaymentIntent intent) return null;
return new DomainPaymentEvent(
Type: DomainPaymentEventType.PaymentSucceeded,
ExternalReference: intent.Id,
Amount: new Money(intent.Amount / 100m, intent.Currency.ToUpperInvariant()));
}
private static DomainPaymentEvent? TranslateFailed(Event e)
{
if (e.Data.Object is not PaymentIntent intent) return null;
return new DomainPaymentEvent(
Type: DomainPaymentEventType.PaymentFailed,
ExternalReference: intent.Id,
Amount: null);
}
private static DomainPaymentEvent? TranslateRefunded(Event e)
{
if (e.Data.Object is not Charge charge) return null;
return new DomainPaymentEvent(
Type: DomainPaymentEventType.PaymentRefunded,
ExternalReference: charge.PaymentIntentId,
Amount: new Money(charge.AmountRefunded / 100m, charge.Currency.ToUpperInvariant()));
}
private static DomainPaymentEvent? TranslateDispute(Event e)
{
if (e.Data.Object is not Dispute dispute) return null;
return new DomainPaymentEvent(
Type: DomainPaymentEventType.DisputeOpened,
ExternalReference: dispute.ChargeId,
Amount: new Money(dispute.Amount / 100m, dispute.Currency.ToUpperInvariant()));
}
}
// Clean controller — receives domain events, not Stripe events
[HttpPost("webhooks/payments")]
public async Task<IActionResult> PaymentWebhook()
{
var payload = await new StreamReader(Request.Body).ReadToEndAsync();
var signature = Request.Headers["Stripe-Signature"].ToString();
var domainEvent = await _webhookTranslator.TranslateAsync(payload, signature);
if (domainEvent is null)
return BadRequest();
await _paymentEventHandler.HandleAsync(domainEvent);
return Ok();
}
Cambiando de proveedor sin tocar el dominio
Aquí es donde la inversión se paga. Si necesitas cambiar de Stripe a PayPal:
// New ACL implementation — everything Stripe is gone from this file
public class PayPalPaymentGateway : IPaymentGateway
{
private readonly PayPalHttpClient _client;
public async Task<PaymentResult> ChargeAsync(
PaymentRequest request,
CancellationToken ct = default)
{
// Translate domain request → PayPal request
var paypalOrder = TranslateToPayPalOrder(request);
var response = await _client.Execute(new OrdersCreateRequest().RequestBody(paypalOrder));
// Translate PayPal response → domain result
return TranslateFromPayPal(response.Result<Order>());
}
private static PaymentResult TranslateFromPayPal(Order order) =>
new(
Success: order.Status == "COMPLETED",
Payment: new Payment
{
Id = new PaymentId(order.Id),
Status: TranslatePayPalStatus(order.Status),
Provider = PaymentProvider.PayPal,
ExternalReference = order.Id,
// ...
},
ErrorMessage: null,
RequiresAction: order.Status == "PAYER_ACTION_REQUIRED",
ActionUrl: order.Links?.FirstOrDefault(l => l.Rel == "payer-action")?.Href);
private static PaymentStatus TranslatePayPalStatus(string status) =>
status switch
{
"CREATED" => PaymentStatus.Pending,
"SAVED" => PaymentStatus.Pending,
"APPROVED" => PaymentStatus.Authorised,
"COMPLETED" => PaymentStatus.Captured,
"VOIDED" => PaymentStatus.Declined,
_ => PaymentStatus.Pending
};
}
Cambia una línea en Program.cs:
// Before
builder.Services.AddScoped<IPaymentGateway, StripePaymentGateway>();
// After
builder.Services.AddScoped<IPaymentGateway, PayPalPaymentGateway>();
El dominio, la capa de servicio, los controllers — sin cambios. El ACL absorbió la migración.
Errores habituales
Error 1: poner lógica de traducción en el dominio
// ❌ Domain entity knows how to parse Stripe responses
public class Order
{
public void ApplyStripeWebhook(StripeEvent e)
{
if (e.Type == "payment_intent.succeeded")
Status = OrderStatus.Paid;
}
}
El dominio nunca debería importar tipos del SDK externo. Si ves using Stripe; en una clase de dominio, falta el ACL.
Error 2: filtrar IDs a través de la frontera
// ❌ External ID stored as a first-class domain concept
public class Order
{
public string StripePaymentIntentId { get; set; } // Stripe concept in domain
}
// ✅ Store as an opaque external reference
public class Order
{
public string? ExternalPaymentReference { get; private set; } // domain concept
}
El dominio no sabe ni le importa que ExternalPaymentReference sea un ID de PaymentIntent de Stripe. Es solo una referencia a algo externo.
Error 3: convertir el ACL en un simple pass-through
// ❌ No translation — just wrapping the call
public class StripePaymentGateway : IPaymentGateway
{
public async Task<PaymentIntent> ChargeAsync(PaymentIntentCreateOptions options)
{
return await _stripe.PaymentIntents.CreateAsync(options);
}
}
Si tu ACL expone tipos externos en sus valores de retorno o parámetros, no es un ACL. Es solo una fachada que da una falsa sensación de protección.
Error 4: un único ACL para todo
Si tu sistema integra un proveedor de pagos, una API de envíos, un CRM y un servicio de email, cada uno merece su propio ACL. Mezclarlos crea el mismo problema de acoplamiento que intentabas resolver.
Domain
├── Payments/
│ ├── IPaymentGateway.cs ← domain port
│ └── Infrastructure/
│ └── StripePaymentGateway.cs ← ACL for Stripe
├── Shipping/
│ ├── IShippingProvider.cs ← domain port
│ └── Infrastructure/
│ └── DhlShippingProvider.cs ← ACL for DHL
└── Notifications/
├── IEmailSender.cs ← domain port
└── Infrastructure/
└── SendGridEmailSender.cs ← ACL for SendGrid
Buenas prácticas
Mantén los tipos externos fuera de las interfaces de dominio. Si IPaymentGateway tiene un método que acepta o devuelve un tipo de Stripe, el ACL ha fallado. Las interfaces de dominio usan solo tipos de dominio.
Pon toda la traducción en un único lugar. El mapeo de los estados de Stripe a PaymentStatus debería vivir en exactamente un método. Cuando Stripe añada un estado nuevo, cambias una expresión switch.
Nombra el ACL por lo que provee, no por lo que envuelve. IPaymentGateway es mejor que IStripeAdapter. Tu dominio no sabe que está hablando con Stripe.
Escribe tests para la lógica de traducción. El ACL es donde se esconden los bugs sutiles — un mapeo de estado que falta, una conversión de moneda incorrecta, un código de error mal interpretado. Testea unitariamente los métodos de traducción directamente.
[Theory]
[InlineData("succeeded", PaymentStatus.Captured)]
[InlineData("requires_action", PaymentStatus.RequiresAction)]
[InlineData("canceled", PaymentStatus.Declined)]
[InlineData("processing", PaymentStatus.Pending)]
public void TranslateStripeStatus_MapsCorrectly(string stripeStatus, PaymentStatus expected)
{
var result = StripeStatusTranslator.Translate(stripeStatus);
Assert.Equal(expected, result);
}
Deja que el ACL absorba también los errores. No permitas que StripeException se propague al dominio. Captúrala en el ACL y tradúcela a un resultado de dominio. El dominio nunca debería gestionar excepciones del proveedor de pagos.
Conclusión
La contaminación que describía al principio — StripeChargeId en Order, PSPCONFIRMED en el enum de estado, MapFromStripeWebhookPayload() en la capa de servicio — no era inevitable. Ocurrió gradualmente, un atajo cada vez, cada uno razonable de forma aislada.
El Anti-Corruption Layer es la decisión estructural que hace que esos atajos sean imposibles. Dice: esta es la frontera. En este lado, hablamos nuestro idioma. En ese lado, hablan el suyo. Aquí es donde ocurre la traducción.
Los beneficios se acumulan lentamente y luego se pagan todos de golpe: cuando Stripe deprecia un endpoint, solo cambia el ACL. Cuando añades un segundo proveedor de pagos, añades un segundo ACL. Cuando un nuevo desarrollador se une al equipo, puede entender el flujo de pagos sin conocer el modelo de objetos de Stripe.
El dominio se mantiene limpio. El sistema externo se mantiene externo. La capa de traducción absorbe el caos para que todo lo demás no tenga que hacerlo.
Código fuente completo: github.com/AdrianBailador/anti-corruption-layer-dotnet
¿Preguntas o sugerencias? Abre un issue en GitHub.

