Lewee.Infrastructure.Refit
0.40.3
dotnet add package Lewee.Infrastructure.Refit --version 0.40.3
NuGet\Install-Package Lewee.Infrastructure.Refit -Version 0.40.3
<PackageReference Include="Lewee.Infrastructure.Refit" Version="0.40.3" />
<PackageVersion Include="Lewee.Infrastructure.Refit" Version="0.40.3" />
<PackageReference Include="Lewee.Infrastructure.Refit" />
paket add Lewee.Infrastructure.Refit --version 0.40.3
#r "nuget: Lewee.Infrastructure.Refit, 0.40.3"
#:package Lewee.Infrastructure.Refit@0.40.3
#addin nuget:?package=Lewee.Infrastructure.Refit&version=0.40.3
#tool nuget:?package=Lewee.Infrastructure.Refit&version=0.40.3
Lewee.Infrastructure.Refit
Domain-driven design infrastructure for Refit-based HTTP client communication. This package provides infrastructure layer components that integrate Refit with domain-driven development patterns, including automatic authentication token propagation, distributed correlation ID tracking, and structured API exception handling that aligns with DDD principles.
Dependencies
- Refit.HttpClientFactory - Type-safe REST client with HttpClientFactory integration
- Correlate.AspNetCore - Correlation ID functionality for ASP.NET Core
- Lewee.Common - Shared utilities and constants
- Lewee.Infrastructure.Auth - Authentication infrastructure including token handling
Features
This infrastructure package provides:
- Refit Client Configuration: Streamlined setup of type-safe HTTP clients that integrate seamlessly with domain and application layers
- Authentication Infrastructure: Automatic Bearer token propagation from the current user context to external APIs
- Correlation ID Infrastructure: Built-in distributed tracing support using Correlate to track requests across service boundaries
Configuration
Infrastructure layer services are registered using standard ASP.NET Core dependency injection. In the code below, services is Microsoft.Extensions.DependencyInjection.IServiceCollection.
Registering Refit API Clients
Use AddWebApiHttpClient<T> to configure type-safe Refit clients as infrastructure services:
using Lewee.Infrastructure.Refit;
// Register API client infrastructure with service discovery
services.AddWebApiHttpClient<IMyApiClient>("my-api-service");
This automatically configures infrastructure components:
AuthTokenDelegatingHandler(from Lewee.Infrastructure.Auth) - Infrastructure handler that adds Bearer tokens from the authentication contextCorrelatingHttpMessageHandler(from Correlate) - Infrastructure handler that propagates correlation IDs across service boundaries- Refit reflection support for JSON serialization and deserialization of client contracts
Service Discovery Integration
The AddWebApiHttpClient<T> method integrates with .NET Aspire service discovery for infrastructure layer service location:
// In your AppHost (infrastructure orchestration)
var api = builder.AddProject<Projects.MyApi>("my-api-service");
// In your client application (infrastructure registration)
services.AddWebApiHttpClient<IMyApiClient>("my-api-service");
Usage in Domain-Driven Design
Defining Infrastructure Interfaces
Define Refit interfaces in your infrastructure layer to communicate with external APIs:
using Refit;
// Infrastructure interface for external API communication
public interface IOrdersApiClient
{
[Get("/api/orders")]
Task<IEnumerable<OrderDto>> GetOrdersAsync();
[Get("/api/orders/{id}")]
Task<OrderDto> GetOrderAsync(Guid id);
[Post("/api/orders")]
Task<OrderDto> CreateOrderAsync([Body] CreateOrderRequest request);
[Put("/api/orders/{id}")]
Task UpdateOrderAsync(Guid id, [Body] UpdateOrderRequest request);
[Delete("/api/orders/{id}")]
Task DeleteOrderAsync(Guid id);
}
Register the infrastructure client:
services.AddWebApiHttpClient<IOrdersApiClient>("orders-api");
Using Infrastructure Clients in Application Services
Inject the infrastructure client into your application services or domain service implementations:
public class OrderService
{
private readonly IOrdersApiClient ordersClient;
public OrderService(IOrdersApiClient ordersClient)
{
this.ordersClient = ordersClient;
}
public async Task<OrderDto> GetOrderAsync(Guid id)
{
return await this.ordersClient.GetOrderAsync(id);
}
}
Integration with Application Layer Effects
When using with Fluxor state management in the application layer, handle infrastructure errors in effects:
using Fluxor;
using Lewee.Infrastructure.Refit;
public class OrderEffects
{
private readonly IOrdersApiClient apiClient;
private readonly ILogger<OrderEffects> logger;
public OrderEffects(IOrdersApiClient apiClient, ILogger<OrderEffects> logger)
{
this.apiClient = apiClient;
this.logger = logger;
}
[EffectMethod]
public async Task CreateOrderAsync(CreateOrderAction action, IDispatcher dispatcher)
{
try
{
var order = await this.apiClient.CreateOrderAsync(action.Request);
dispatcher.Dispatch(new CreateOrderSuccessAction
{
CorrelationId = action.CorrelationId,
Order = order
});
}
catch (Exception ex)
{
this.logger.LogError(ex, "Failed to create order");
dispatcher.Dispatch(new CreateOrderFailureAction
{
CorrelationId = action.CorrelationId,
ErrorMessage = ex.Message
});
}
}
}
Infrastructure Components
| Component | Description |
|---|---|
| ApiCientConfiguration.cs | Infrastructure service registration with AddWebApiHttpClient<T> |
Distributed Correlation ID Infrastructure
This infrastructure package uses Correlate to automatically propagate correlation IDs across service boundaries. The CorrelatingHttpMessageHandler adds the X-Correlation-ID header to all outgoing HTTP requests.
Correlation IDs flow through the infrastructure layers:
- Incoming HTTP requests (via Correlate middleware in infrastructure)
- Outgoing HTTP requests (via
CorrelatingHttpMessageHandlerinfrastructure) - Infrastructure and application layer logging
- Response headers returned through infrastructure
Infrastructure Configuration
The AddWebApiHttpClient<T> method automatically configures the Correlate infrastructure:
services.AddCorrelate(options => options.RequestHeaders = [RequestHeaders.CorrelationId]);
Authentication Infrastructure
The AuthTokenDelegatingHandler (from Lewee.Infrastructure.Auth) provides infrastructure-level authentication token handling:
- Retrieves the
access_tokenfrom the current authentication context (HttpContext) - Adds it as a
Bearertoken in theAuthorizationheader for outgoing requests - Logs infrastructure warnings when authentication tokens are unavailable
This infrastructure is automatically configured when using AddWebApiHttpClient<T>.
Infrastructure Prerequisites
For the authentication infrastructure to function:
IHttpContextAccessormust be registered in the DI container- The user must be authenticated with an
access_tokenin the authentication context HttpContextmust be accessible (supported in Blazor Web Apps with Interactive Server and server-side rendering scenarios)
Integration with Lewee DDD Layers
This infrastructure package integrates with other Lewee packages across the DDD layers:
| Package | Layer | Integration |
|---|---|---|
| Lewee.Common | Cross-cutting | Provides RequestHeaders.CorrelationId constant for infrastructure |
| Lewee.Infrastructure.Auth | Infrastructure | Provides AuthTokenDelegatingHandler for automatic authentication token propagation |
Best Practices for DDD Infrastructure
- Service Discovery: Use .NET Aspire service discovery rather than hardcoded URIs for infrastructure service location
- Distributed Tracing: Leverage correlation IDs for tracing requests across infrastructure boundaries
- Bounded Context Separation: Define focused Refit interfaces per bounded context or aggregate
- REST Conventions: Follow REST principles in infrastructure interface definitions to align with domain semantics
Troubleshooting Infrastructure Issues
Authentication Infrastructure Issues
- Ensure
AuthTokenDelegatingHandleris configured (automatic withAddWebApiHttpClient) - Verify the user is authenticated with an
access_tokenin the authentication context - Check
HttpContextaccessibility in your hosting model - For Blazor WebAssembly, authentication infrastructure requires different handling
Correlation ID Infrastructure Issues
- Verify
CorrelatingHttpMessageHandleris configured (automatic withAddWebApiHttpClient) - Ensure Correlate middleware is configured in server infrastructure
- Check that the server infrastructure echoes correlation IDs in responses
Service Discovery Infrastructure Issues
- Ensure your AppHost defines the infrastructure service with the correct name
- Verify service discovery infrastructure is configured in your client application
- Check that the infrastructure service is running and healthy
Refit Infrastructure Serialization Issues
- Ensure DTOs match the API contract (consider using shared contract assemblies)
- Check JSON serialization settings are consistent across infrastructure boundaries
- Use
[Body]attribute for request bodies in infrastructure interfaces - Use
[Query]attribute for query parameters in infrastructure interfaces
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net11.0 is compatible. |
-
net11.0
- Correlate.AspNetCore (>= 6.1.1)
- Lewee.Common (>= 0.40.3)
- Lewee.Infrastructure.Auth (>= 0.40.3)
- Refit.HttpClientFactory (>= 17.0.0)
- Refit.Reflection (>= 17.0.0)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 0.40.3 | 49 | 11/22/2026 |