ExternalApiHttpAdapter provides a robust HTTP client implementation with built-in resilience patterns using Polly for calling external APIs.
ExternalApiHttpAdapter
Class Definition
Core.Infraestructure.Adapters.Http/ExternalApiHttpAdapter.cs
Constructor
- An
HttpClientinstance - A combined retry and circuit breaker policy
- A logger for diagnostics
Resilience Policies
The adapter combines two Polly policies for maximum resilience:1. Retry Policy
Exponential backoff retry with 3 attempts:- Attempt 1: Immediate
- Attempt 2: After 2 seconds
- Attempt 3: After 4 seconds
- Attempt 4: After 8 seconds (if needed)
2. Circuit Breaker Policy
Prevents cascading failures by opening the circuit after repeated failures:- Closed: Normal operation, requests flow through
- Open: After 5 failures, circuit opens for 30 seconds, rejecting all requests
- Half-Open: After 30 seconds, allows one test request
Combined Policy
HTTP Methods
GET Request
POST Request
PUT Request
DELETE Request
Authentication
The adapter supports two authentication schemes:Bearer Token Authentication
Basic Authentication
Custom Headers
Add custom headers to any request:Error Handling
The adapter automatically checks for common HTTP errors:500 Internal Server Error: Throws HttpRequestException400 Bad Request: Throws HttpRequestException401 Unauthorized: Throws HttpRequestException
Service Registration
Register the adapter as a singleton in your DI container:Infrastructure/Registrations/InfraestructureServicesRegistration.cs
Usage in Startup/Program.cs
JSON Serialization
The adapter uses Newtonsoft.Json for request serialization:TLS Configuration
The adapter enforces TLS 1.2:Complete Usage Example
1. Define Request/Response Models
2. Create Service
3. Register Service
4. Use Service
Key Features
- Retry Logic: Exponential backoff with configurable retry count
- Circuit Breaker: Prevents cascading failures
- Authentication: Support for Bearer and Basic authentication
- Custom Headers: Add custom headers to any request
- Error Handling: Automatic error detection and exception throwing
- TLS 1.2: Enforces secure connections
- JSON Serialization: Automatic serialization using Newtonsoft.Json
- Logging: Comprehensive logging for diagnostics
- Resilience: Combined policies for maximum reliability