Features of the ConnectSoft API Library Template¶
The ConnectSoft API Library Template offers a comprehensive set of features designed to simplify the development of robust, reusable, and resilient API service agent libraries. It provides pre-configured components, best practices, and extensibility for diverse use cases.
Core Features¶
Typed HTTP Client¶
The template implements a strongly-typed HTTP client using HttpClientFactory for optimal performance and resource management.
HttpClientFactory Integration¶
- Connection Pooling: Efficient reuse of HTTP connections, reducing overhead and improving performance.
- DNS Updates: Automatic handling of DNS changes without requiring application restarts.
- Lifecycle Management: Proper disposal and lifecycle management of HTTP clients.
- Thread Safety: Thread-safe HTTP client instances suitable for concurrent use.
Strongly-Typed Interfaces¶
- Interface-Based Design: Service contracts defined through interfaces (
I{ServiceName}Service). - Type Safety: Compile-time type checking for API requests and responses.
- IntelliSense Support: Full IntelliSense support for API methods and parameters.
Example¶
public interface IGoogleAnalyticsService
{
Task<GoogleAnalyticsResult> GetDataAsync(CancellationToken cancellationToken = default);
}
public class GoogleAnalyticsService : IGoogleAnalyticsService
{
private readonly HttpClient _httpClient;
private readonly ILogger<GoogleAnalyticsService> _logger;
public GoogleAnalyticsService(
HttpClient httpClient,
ILogger<GoogleAnalyticsService> logger)
{
_httpClient = httpClient;
_logger = logger;
}
public async Task<GoogleAnalyticsResult> GetDataAsync(CancellationToken cancellationToken = default)
{
var request = new HttpRequestMessage(HttpMethod.Get, "/api/data");
var response = await _httpClient.SendAsync(request, cancellationToken);
response.EnsureSuccessStatusCode();
// ... deserialize and return result
}
}
Authentication Mechanisms¶
The template supports multiple authentication mechanisms, allowing you to choose the appropriate method for your API.
None Authentication¶
- Use Case: Public APIs that don't require authentication.
- Configuration: No authentication configuration needed.
- Implementation: HTTP client configured without authentication headers.
Basic Authentication¶
- Use Case: APIs using HTTP Basic Authentication (username/password).
- Configuration: Requires
UsernameandPasswordinBasicAuthenticationOptions. - Implementation: Base64-encoded credentials in
Authorizationheader. - Generated Files:
BasicAuthenticationOptions.cs(whenAuthenticationType=Basic).
API Key Authentication¶
- Use Case: APIs that use API keys in headers or query strings.
- Configuration: Requires
ApiKeyand optionalHeaderName(default:X-Api-Key). - Implementation: API key added to request headers.
- Generated Files:
ApiKeyAuthenticationOptions.cs(whenAuthenticationType=ApiKey).
OAuth2 Authentication¶
- Use Case: APIs using OAuth 2.0 client credentials flow.
- Configuration: Requires OAuth2 client options (client ID, client secret, token endpoint, scopes).
- Implementation: Automatic token acquisition and refresh using
ConnectSoft.Extensions.Http.OAuth2. - Package: Adds
ConnectSoft.Extensions.Http.OAuth2package reference.
OpenID Connect Authentication¶
- Use Case: APIs using OpenID Connect with identity provider integration.
- Configuration: Requires OAuth2 options plus OpenID Connect authority and validation settings.
- Implementation: Token acquisition with OpenID Connect token validation.
- Package: Adds
ConnectSoft.Extensions.Http.OAuth2package reference.
For detailed authentication documentation, see the Authentication Guide.
Resiliency Patterns¶
The template includes comprehensive resiliency patterns to handle transient failures and ensure reliable API communication.
Standard Resilience Handler¶
The standard resilience handler provides a layered approach to fault tolerance:
- Bulkhead: Limits the maximum number of concurrent requests to prevent resource exhaustion.
- Total Request Timeout: Applies an overall timeout to the entire request execution.
- Retry: Retries the request in case of transient errors.
- Circuit Breaker: Blocks execution if too many failures are detected.
- Attempt Timeout: Limits each request attempt duration.
Configuration:
{
"EnableHttpStandardResilience": true,
"HttpStandardResilience": {
"TotalRequestTimeout": { "Timeout": "00:00:30" },
"Retry": {
"MaxRetryAttempts": 3,
"BackoffType": "Constant",
"Delay": "00:00:02"
},
"CircuitBreaker": {
"FailureRatio": 0.1,
"MinimumThroughput": 2,
"SamplingDuration": "00:00:30",
"BreakDuration": "00:00:05"
},
"AttemptTimeout": { "Timeout": "00:00:10" },
"RateLimiter": {
"DefaultRateLimiterOptions": {
"PermitLimit": 1000,
"QueueLimit": 0
}
}
}
}
Standard Hedging Handler¶
The standard hedging handler executes requests against multiple endpoints in parallel for slow dependencies:
- Total Request Timeout: Overall timeout for the hedging execution.
- Hedging: Parallel request execution with configurable delay and max attempts.
- Endpoint-Specific Strategies: Bulkhead, circuit breaker, and attempt timeout per endpoint.
Configuration:
{
"EnableHttpStandardHedgingResilience": true,
"HttpStandardHedgingResilience": {
"TotalRequestTimeout": { "Timeout": "00:00:30" },
"Hedging": {
"Delay": "00:00:02",
"MaxHedgedAttempts": 1
},
"Endpoint": {
"RateLimiter": { /* ... */ },
"CircuitBreaker": { /* ... */ },
"Timeout": { "Timeout": "00:00:10" }
}
}
}
Polly Integration¶
The template uses Polly.Core for advanced resilience patterns:
- Retry Policies: Configurable retry strategies with exponential backoff.
- Circuit Breaker: Prevents cascading failures.
- Bulkhead Isolation: Resource throttling and isolation.
- Rate Limiting: API rate policy compliance.
For detailed resiliency documentation, see the Resiliency & Chaos Guide.
Chaos Injection¶
Chaos injection allows you to test your library's resiliency by simulating failures and delays.
Features¶
- Fault Injection: Simulates exceptions and errors.
- Latency Injection: Adds delays to simulate slow network conditions.
- Outcome Injection: Simulates HTTP error responses.
Configuration¶
{
"EnableChaosInjection": true,
"ChaosInjection": {
"InjectionRate": 0.001, // 0.1% of requests
"Latency": "00:00:05" // 5 second delay
}
}
Use Cases:
- Testing retry mechanisms
- Validating circuit breaker behavior
- Verifying timeout handling
- Stress testing under failure conditions
For detailed chaos engineering documentation, see the Resiliency & Chaos Guide.
Metrics (UseMetrics)¶
When UseMetrics is true (default), the template includes comprehensive metrics support using System.Diagnostics.Metrics (OpenTelemetry compatible).
Custom Metrics Implementation¶
The generated metrics class provides:
- Request Counter: Tracks the total number of API requests.
- Request Duration Histogram: Measures request processing time.
- Failure Counter: Tracks failed requests.
- Failure by Status Code Counter: Groups failures by HTTP status code.
Example¶
public class GoogleAnalyticsServiceMetrics
{
private readonly Counter<long> requestCounter;
private readonly Histogram<double> requestDuration;
private readonly Counter<long> requestFailureCounter;
private readonly Counter<long> requestFailureByStatusCode;
public void IncrementRequestCounter() => requestCounter.Add(1);
public void RecordRequestProcessingTime(double durationMilliseconds)
=> requestDuration.Record(durationMilliseconds);
public void IncrementFailure() => requestFailureCounter.Add(1);
public void IncrementFailureByStatusCode(int statusCode)
=> requestFailureByStatusCode.Add(1, new KeyValuePair<string, object?>("status_code", statusCode));
}
OpenTelemetry Integration¶
Metrics are compatible with OpenTelemetry and can be exported to:
- Prometheus
- Azure Monitor
- Grafana
- Other OpenTelemetry-compatible backends
For detailed metrics documentation, see the Configuration Guide.
Configuration and Options¶
The template uses the .NET Options pattern for strongly-typed, validated configuration.
Options Pattern¶
- Strongly-Typed Configuration: Configuration bound to C# classes.
- Validation: DataAnnotations and source-generated validators.
- Nested Options: Complex configuration structures supported.
- Environment Variables: Externalized configuration support.
Service Options¶
The main service options class ({ServiceName}ServiceOptions) includes:
- BaseUrl: API base URL (required, validated as URL).
- DefaultTimeout: Request timeout (required, validated range).
- WebProxy: Proxy configuration (nested options).
- EnableHttpStandardResilience: Toggle for standard resilience.
- HttpStandardResilience: Standard resilience options (nested).
- EnableHttpStandardHedgingResilience: Toggle for hedging.
- HttpStandardHedgingResilience: Hedging options (nested).
- EnableChaosInjection: Toggle for chaos injection.
- ChaosInjection: Chaos injection options (nested).
- Authentication Options: Conditional based on
AuthenticationType.
Validation¶
- DataAnnotations: Required fields, data types, ranges.
- Source-Generated Validators: Compile-time validation generation.
- Startup Validation: Configuration validated at application startup.
For detailed configuration documentation, see the Configuration Guide.
Web Proxy Support¶
The template includes configurable web proxy support for HTTP requests.
Configuration¶
Implementation¶
- SocketsHttpHandler: Configured with proxy settings.
- Connection Pooling: Proxy-aware connection pooling.
- Bypass Rules: Configurable proxy bypass rules.
Mock Server Testing¶
The template includes WireMock.Net integration for mock server testing.
Features¶
- API Simulation: Simulates API responses without requiring the actual API.
- Configurable Endpoints: Define mock endpoints for various scenarios.
- Request Matching: Match requests by URL, method, headers, body.
- Response Stubbing: Define mock responses with status codes, headers, body.
Example¶
[TestMethod]
public async Task GetDataAsync_WithMockedServer_ReturnsSuccess()
{
using var server = WireMockServer.Start();
server.Given(Request.Create()
.WithPath("/api/data")
.UsingGet())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithBodyAsJson(new { data = "test" }));
// Configure service to use mock server URL
// ... test implementation
}
For detailed testing documentation, see the Testing Guide.
Multi-Targeting¶
The template supports multi-targeting for both .NET 8 (LTS) and .NET 9.
Target Frameworks¶
- .NET 8.0: Long-term support (LTS) version.
- .NET 9.0: Latest version with new features.
Benefits¶
- Broader Compatibility: Single NuGet package supports multiple .NET versions.
- Future-Proof: Easy migration path to newer .NET versions.
- Conditional Compilation: Framework-specific code using
#if NET9_0.
Example¶
Static Code Analyzers¶
The template includes built-in static code analyzers for code quality and consistency.
Included Analyzers¶
- StyleCop.Analyzers: Enforces consistent C# style and naming conventions.
- SonarAnalyzer.CSharp: Detects bugs, vulnerabilities, and code smells.
- Meziantou.Analyzer: Provides additional code quality best practices.
- AsyncFixer: Fixes common
async/awaitmistakes. - Asyncify: Ensures correct async method usage.
- Microsoft.VisualStudio.Threading.Analyzers: Enforces threading and async patterns.
Configuration¶
Analyzers are managed centrally via Directory.Build.props, eliminating manual setup in individual .csproj files.
Central Package Management (CPM)¶
The template uses Central Package Management (CPM) to simplify and standardize NuGet package versioning.
Benefits¶
- Consistent Versions: All projects use the same package versions.
- Easier Upgrades: Update versions in one place (
Directory.Packages.props). - Cleaner Project Files: Package versions not cluttering individual
.csprojfiles.
Example¶
<!-- Directory.Packages.props -->
<ItemGroup>
<PackageVersion Include="Microsoft.Extensions.Http" Version="9.0.10" />
<PackageVersion Include="Polly.Core" Version="8.6.4" />
</ItemGroup>
<!-- Project.csproj -->
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Http" />
<PackageReference Include="Polly.Core" />
</ItemGroup>
Solution Format (.slnx)¶
The template generates a modern .slnx (XML-based) solution file format.
Benefits¶
- Improved Performance: 48% faster CLI builds compared to legacy
.slnformat. - Better IDE Performance: Faster solution loading and navigation.
- XML-Based: Easier to parse and modify programmatically.
Requirements¶
- Visual Studio 2022 v17.14+
- .NET SDK 9.0.200+
Fallback¶
A traditional .sln file is also generated for compatibility with older tools.
CI/CD Integration¶
The template includes a pre-configured Azure DevOps CI/CD pipeline.
Pipeline Features¶
- Multi-Targeting: Builds for both .NET 8 and .NET 9.
- Code Coverage: Collects and enforces code coverage thresholds.
- Build Quality Checks: Validates code quality before publishing.
- NuGet Publishing: Automatically publishes packages to Azure Artifacts.
- Security Checks: Scans for deprecated and vulnerable packages.
Pipeline Steps¶
- Install .NET SDKs (8.x and 9.x)
- NuGet authentication
- Restore packages
- Check deprecated packages
- Check package vulnerabilities
- Build solution
- Run tests with code coverage
- Publish code coverage report
- Build quality checks
- Pack NuGet package
- Push to Azure Artifacts
For detailed pipeline documentation, see the Runbook.
Advanced Features¶
Structured Logging¶
The template integrates structured logging using Microsoft.Extensions.Logging.
Features¶
- ILogger
: Strongly-typed logging with service context. - Structured Logging: Log entries with structured data for better queryability.
- Log Levels: Support for Trace, Debug, Information, Warning, Error, Critical.
- Log Correlation: Integration with distributed tracing (when available).
Example¶
_logger.LogInformation("Request to {Endpoint} completed with status {StatusCode}",
endpoint, statusCode);
Exception Handling¶
The template includes custom exception classes for API-specific errors.
Features¶
- Custom Exceptions:
{ServiceName}ServiceExceptionfor API errors. - Error Context: Exceptions include context about the API failure.
- Inner Exceptions: Preserves original exceptions for debugging.
Example¶
try
{
// API call
}
catch (Exception ex)
{
_logger.LogError(ex, "Error fetching data");
throw new GoogleAnalyticsServiceException("Error fetching data", ex);
}
Request/Response Models¶
The template generates request and response model structures.
Generated Models¶
- Response Models:
{ServiceName}Response.csfor API responses. - Result Models:
{ServiceName}Result.csfor processed results. - Error Models:
{ServiceName}Error.csfor error details.
JSON Serialization¶
- System.Text.Json: Default JSON serializer.
- Property Naming: Configurable property naming (camelCase, PascalCase).
- Custom Converters: Support for custom JSON converters.
Testing Features¶
Unit Testing¶
- MSTest Framework: Pre-configured MSTest for unit testing.
- Code Coverage: Integrated code coverage collection.
- Test Organization: Tests organized by feature and scenario.
Integration Testing¶
- Mock Server: WireMock.Net for API simulation.
- End-to-End Tests: Tests with real or mocked APIs.
- Configuration: Separate configuration files for test scenarios.
Chaos Testing¶
- Fault Injection: Simulates failures for resiliency validation.
- Latency Injection: Tests timeout and retry mechanisms.
- Error Simulation: Validates error handling and recovery.
For detailed testing documentation, see the Testing Guide.
Best Practices Embedded¶
Separation of Concerns¶
- Service Layer: API interaction logic isolated in service classes.
- Options Layer: Configuration separated from implementation.
- Metrics Layer: Observability separated from business logic.
Secure by Default¶
- HTTPS Enforcement: Base URLs validated for HTTPS (where applicable).
- Secure Authentication: Secure handling of credentials and tokens.
- Input Validation: Configuration validated at startup.
Observability¶
- Structured Logging: Comprehensive logging for debugging and monitoring.
- Metrics: Performance and health metrics for production monitoring.
- Error Tracking: Detailed error information for troubleshooting.
Reusability¶
- Interface-Based Design: Easy to mock and test.
- Dependency Injection: Loose coupling for flexibility.
- NuGet Publishing: Easy distribution and versioning.
Roadmap Features¶
The following features are planned for future releases:
- Serialization Support: Advanced serialization for XML, JSON, and Protobuf payloads.
- Content Negotiation: Automatic handling of
Acceptheaders for dynamic content types. - Compression Support: GZip and Brotli compression for HTTP requests and responses.
- Service Discovery: Integration with service registries like Consul and Eureka.
- Caching: Response caching using Redis or in-memory providers.
- Advanced Instrumentation: Enhanced metrics for SLA tracking.
- Additional Authentication: Support for SAML and user delegation (on-behalf-of).
Conclusion¶
The ConnectSoft API Library Template provides a comprehensive foundation for building robust, maintainable, and resilient API service agent libraries. By integrating typed HTTP clients, advanced resiliency patterns, comprehensive testing tools, and CI/CD workflows, it sets a new standard for .NET Core API libraries.
Each feature is designed to work seamlessly together, providing a cohesive development experience that follows industry best practices and modern .NET patterns.