Skip to content

Generated Structure of the ConnectSoft API Library Template

The ConnectSoft API Library Template generates a well-defined and organized solution structure designed for clarity, maintainability, and adherence to modern .NET development practices. This document provides a detailed breakdown of the files and folders created, explaining their purpose and how they contribute to the overall API library project.

The structure is dynamic, adapting based on the parameters selected during template instantiation (e.g., AuthenticationType, UseMetrics).

Solution Root Directory

When you create a new API library (e.g., ConnectSoft.GoogleAnalytics), a root directory with the specified name is created.

ConnectSoft.GoogleAnalytics/
├── .git/                                 # Git repository metadata
├── .template.config/                     # .NET Template configuration files (not part of generated project)
├── .vs/                                  # Visual Studio solution user options (ignored by Git)
├── docs/                                 # MkDocs documentation structure (optional)
├── azure-pipelines.yml                   # Azure DevOps CI/CD pipeline definition
├── ConnectSoft.GoogleAnalytics.slnx     # Modern XML-based solution file (recommended)
├── ConnectSoft.GoogleAnalytics.sln       # Traditional Visual Studio solution file (fallback)
├── ConnectSoft.GoogleAnalytics.runsettings # MSTest run settings for code coverage and analyzers
├── Directory.Build.props                 # MSBuild properties shared across all projects
├── Directory.Packages.props              # Central Package Management (CPM) for NuGet versions
├── README.md                             # Project overview and documentation entry point
├── nuget.config                          # NuGet feed configuration
├── .gitignore                            # Git ignore rules
├── src/                                  # Source code for the main library project
│   └── ConnectSoft.GoogleAnalytics/      # Main library project directory
│       ├── ConnectSoft.GoogleAnalytics.csproj
│       ├── IGoogleAnalyticsService.cs
│       ├── GoogleAnalyticsService.cs
│       ├── GoogleAnalyticsServiceException.cs
│       ├── GoogleAnalyticsResponse.cs
│       ├── GoogleAnalyticsResult.cs
│       ├── GoogleAnalyticsError.cs
│       ├── GoogleAnalyticsServiceExtensions.cs
│       ├── Options/                      # Configuration options
│       ├── Metrics/                      # (Conditional) Custom metrics implementation
│       ├── Handlers/                     # (Empty) For custom HTTP message handlers
│       ├── Resilience/                   # (Empty) For custom resilience policies
│       └── GlobalSuppressions.cs         # Global code analysis suppressions
└── tests/                                # Test projects
    └── ConnectSoft.GoogleAnalytics.UnitTests/  # Unit test project directory
        ├── ConnectSoft.GoogleAnalytics.UnitTests.csproj
        ├── GoogleAnalyticsServiceUnitTests.cs
        ├── GoogleAnalyticsServiceWithMockedServerUnitTests.cs
        ├── Metrics/                      # (Conditional) Unit tests for metrics
        ├── appsettings.UnitTests.json
        ├── appsettings.MockedServerUnitTests.json
        └── GlobalSuppressions.cs         # Global code analysis suppressions for tests

Key Files and Directories Explained

Solution Files

  • ConnectSoft.GoogleAnalytics.slnx:

    • The primary solution file. This is a modern, XML-based solution format that offers improved performance, especially for large solutions. It's recommended for Visual Studio 2022 v17.14+ and .NET SDK 9.0.200+.
    • Benefits: 48% faster CLI builds compared to legacy .sln format, better IDE performance.
  • ConnectSoft.GoogleAnalytics.sln:

    • A traditional Visual Studio solution file, included as a fallback for older IDE versions or specific build environments.

Configuration and Build

  • Directory.Build.props:

    • An MSBuild file that defines properties and item groups that are automatically imported into all .csproj files in the solution and its subdirectories.
    • Key Properties:
      • NuGetAudit: Enables NuGet security auditing
      • NuGetAuditMode: Audit mode (direct dependencies)
      • NuGetAuditLevel: Minimum audit level (moderate)
      • ImplicitUsings: Disabled for explicit control
      • Authors and Company: ConnectSoft metadata
    • Static Code Analyzers: References to StyleCop, SonarAnalyzer, Meziantou.Analyzer, AsyncFixer, Asyncify, and Microsoft.VisualStudio.Threading.Analyzers
  • Directory.Packages.props:

    • This file implements Central Package Management (CPM). It centralizes the management of NuGet package versions across all projects in the solution.
    • Key Packages:
      • Microsoft.Extensions.Http and Microsoft.Extensions.Http.Resilience
      • Polly.Core
      • Microsoft.Extensions.Logging.Abstractions
      • Microsoft.Extensions.Options and Microsoft.Extensions.Options.DataAnnotations
      • ConnectSoft.Extensions.Http.OAuth2 (conditional, for OAuth/OpenIDConnect)
      • Microsoft.Extensions.Diagnostics (conditional, for UseMetrics)
      • WireMock.Net (for testing)
      • Static code analyzers
  • ConnectSoft.GoogleAnalytics.runsettings:

    • A .runsettings file used by MSTest to configure test execution, including code coverage filters, data collectors, and other test-related settings.

Documentation

  • README.md:
    • The main documentation file for the generated library. It provides an overview, key features, usage instructions, and references. It's pre-populated with placeholders that should be replaced with actual API-specific information.

CI/CD Pipeline

  • azure-pipelines.yml:
    • The Azure DevOps YAML pipeline definition. It orchestrates the automated build, test, code coverage analysis, and NuGet package publishing process.
    • Features:
      • Multi-targeting support (.NET 8 and .NET 9)
      • Code coverage enforcement
      • Build quality checks
      • NuGet package creation and publishing
      • Security checks (deprecated and vulnerable packages)
    • For a detailed breakdown, refer to the Runbook.

NuGet Configuration

  • nuget.config:
    • Configures NuGet package sources, including Azure DevOps Artifacts feeds for ConnectSoft packages.

Source Project (src/ConnectSoft.GoogleAnalytics/)

This directory contains the core logic of your API client library.

Project File

  • ConnectSoft.GoogleAnalytics.csproj:
    • The project file for the main library. It defines:
      • Target Frameworks: net8.0;net9.0 (multi-targeting)
      • ImplicitUsings: Disabled for explicit control
      • Nullable: Enabled for null safety
      • GenerateDocumentationFile: Enabled for XML documentation
      • ManagePackageVersionsCentrally: Enabled for CPM
      • InternalsVisibleTo: Allows unit tests to access internal members
    • Package References (managed via CPM):
      • Microsoft.Extensions.Http
      • Microsoft.Extensions.Http.Resilience
      • Polly.Core
      • Microsoft.Extensions.Logging.Abstractions
      • Microsoft.Extensions.Options and Microsoft.Extensions.Options.DataAnnotations
      • ConnectSoft.Extensions.Http.OAuth2 (conditional, for OAuth/OpenIDConnect)
      • Microsoft.Extensions.Diagnostics (conditional, for UseMetrics)

Core Service Files

  • IGoogleAnalyticsService.cs:

    • The service interface defining the API contract. Contains method signatures for API operations.
    • Example:
      public interface IGoogleAnalyticsService
      {
          Task<GoogleAnalyticsResult> GetDataAsync(CancellationToken cancellationToken = default);
      }
      
  • GoogleAnalyticsService.cs:

    • The service implementation using HttpClient for API communication. Implements the interface and handles HTTP requests/responses.
    • Key Features:
      • Uses HttpClient injected via constructor
      • Structured logging with ILogger<T>
      • Metrics instrumentation (if UseMetrics=true)
      • Error handling and exception wrapping
      • JSON serialization/deserialization
  • GoogleAnalyticsServiceException.cs:

    • Custom exception class for API-specific errors. Extends Exception and provides context about API failures.
  • GoogleAnalyticsResponse.cs:

    • Response model representing the API response structure. Used for deserializing JSON responses.
  • GoogleAnalyticsResult.cs:

    • Result model representing the processed result returned to consumers. Typically a simplified or transformed version of the response.
  • GoogleAnalyticsError.cs:

    • Error model representing error details in API responses. Used for deserializing error responses.
  • GoogleAnalyticsServiceExtensions.cs:

    • Dependency injection extension methods for registering the service and configuring options.
    • Key Methods:
      • AddGoogleAnalyticsOptions(): Registers and validates options
      • AddGoogleAnalyticsMetrics(): Registers metrics (if UseMetrics=true)
      • AddGoogleAnalyticsService(): Registers the HTTP client and service
    • Configuration:
      • HTTP client configuration (base URL, timeout, headers)
      • Authentication setup (based on AuthenticationType)
      • Resilience handler configuration
      • Chaos injection setup (if enabled)
      • Proxy configuration
  • GlobalSuppressions.cs:

    • Contains global code analysis suppressions, allowing you to manage warnings across the entire project.

Conditional Folders and Files

Options/ Folder

Always generated, but contents vary based on AuthenticationType:

  • GoogleAnalyticsServiceOptions.cs (always generated):

    • Main service options class containing:
      • BaseUrl: API base URL
      • DefaultTimeout: Request timeout
      • WebProxy: Proxy configuration
      • EnableHttpStandardResilience: Resilience toggle
      • HttpStandardResilience: Standard resilience options
      • EnableHttpStandardHedgingResilience: Hedging toggle
      • HttpStandardHedgingResilience: Hedging options
      • EnableChaosInjection: Chaos injection toggle
      • ChaosInjection: Chaos injection options
      • Authentication options (conditional based on AuthenticationType)
  • ValidateGoogleAnalyticsServiceOptions.cs (always generated):

    • Source-generated options validator using [OptionsValidator] attribute.
  • ApiKeyAuthenticationOptions.cs (if AuthenticationType=ApiKey):

    • Options for API key authentication:
      • ApiKey: The API key value
      • HeaderName: Header name (default: X-Api-Key)
  • BasicAuthenticationOptions.cs (if AuthenticationType=Basic):

    • Options for Basic authentication:
      • Username: Username
      • Password: Password
  • ChaosInjectionOptions.cs (always generated):

    • Options for chaos injection:
      • InjectionRate: Rate of injection (0-1)
      • Latency: Latency to inject
  • WebProxyOptions.cs (always generated):

    • Options for web proxy:
      • UseProxy: Whether to use a proxy
      • ProxyAddress: Proxy address (optional)

Metrics/ Folder (if UseMetrics=true)

  • GoogleAnalyticsServiceMetrics.cs:
    • Custom metrics implementation using System.Diagnostics.Metrics.
    • Metrics Provided:
      • request.count: Counter for API requests
      • request.duration: Histogram for request processing time
      • request.failures: Counter for failed requests
      • request.failures.by_status_code: Counter for failures by HTTP status code

Handlers/ Folder

  • Empty folder provided for custom HTTP message handlers. You can add custom handlers here for request/response processing.

Resilience/ Folder

  • Empty folder provided for custom resilience policies. You can add custom Polly policies here if needed.

Test Project (tests/ConnectSoft.GoogleAnalytics.UnitTests/)

This directory contains the unit test project for your API library.

Project File

  • ConnectSoft.GoogleAnalytics.UnitTests.csproj:
    • The project file for the unit tests. It:
      • References the main library project
      • Includes NuGet packages for MSTest and code coverage
      • Includes WireMock.Net for mock server testing
      • Includes Microsoft.Extensions.Diagnostics.Testing (if UseMetrics=true)

Test Files

  • GoogleAnalyticsServiceUnitTests.cs:

    • Unit tests for the service implementation. Tests individual methods and error handling.
  • GoogleAnalyticsServiceWithMockedServerUnitTests.cs:

    • Unit tests using WireMock.Net to simulate API responses. Tests end-to-end scenarios with mocked HTTP responses.
  • appsettings.UnitTests.json:

    • Configuration file for unit tests. Contains test-specific settings, including mock server URLs and test API keys.
  • appsettings.MockedServerUnitTests.json:

    • Configuration file for mock server tests. Contains settings for WireMock server endpoints.

Conditional Test Files

  • Metrics/GoogleAnalyticsServiceMetricsUnitTests.cs (if UseMetrics=true):

    • Unit tests for the metrics implementation, verifying metric instrumentation.
  • GlobalSuppressions.cs:

    • Global code analysis suppressions specific to the test project.

Template File Replacements

The template uses the following replacements throughout the generated code:

Template Token Replaced With Example
ExchangeRate {ApiServiceName} GoogleAnalytics
Exchange rate {ApiServiceDescription} Google Analytics Measurement Protocol API
ConnectSoft.ApiLibraryTemplate {name} ConnectSoft.GoogleAnalytics
net8.0 {Framework} (if specified) net8.0 or net9.0
buildDefinitionNumber {buildDefinitionNumber} 12345

File Renaming

Files are renamed based on ApiServiceName:

  • ExchangeRateService.cs{ApiServiceName}Service.cs
  • IExchangeRateService.csI{ApiServiceName}Service.cs
  • ExchangeRateServiceOptions.cs{ApiServiceName}ServiceOptions.cs
  • And so on for all service-related files.

Namespace Replacements

Namespaces are replaced based on name:

  • namespace ConnectSoft.ApiLibraryTemplatenamespace {name}
  • namespace ConnectSoft.ApiLibraryTemplate.Optionsnamespace {name}.Options
  • namespace ConnectSoft.ApiLibraryTemplate.Metricsnamespace {name}.Metrics

Conditional File Generation

Based on AuthenticationType

AuthenticationType Generated Files
None No authentication options files
Basic BasicAuthenticationOptions.cs
ApiKey ApiKeyAuthenticationOptions.cs
OAuth Uses ConnectSoft.Extensions.Http.OAuth2 package (no additional files)
OpenIDConnect Uses ConnectSoft.Extensions.Http.OAuth2 package (no additional files)

Based on UseMetrics

UseMetrics Generated Files
true Metrics/{ApiServiceName}ServiceMetrics.cs, Metrics/{ApiServiceName}ServiceMetricsUnitTests.cs
false No metrics files

Solution Format (.slnx)

The template generates both .slnx (modern) and .sln (legacy) solution files. The .slnx format provides:

  • Improved Performance: 48% faster CLI builds
  • Better IDE Performance: Faster solution loading and navigation
  • XML-Based: Easier to parse and modify programmatically
  • Modern Format: Recommended for new projects

Requirements:

  • Visual Studio 2022 v17.14+
  • .NET SDK 9.0.200+

Fallback: If .slnx is not supported, use the .sln file.

Documentation Structure (docs/)

If MkDocs documentation is included, the docs/ folder contains:

docs/
├── index.md                    # Documentation homepage
├── api-reference.md            # API reference documentation
├── authentication.md           # Authentication guide
├── configuration.md            # Configuration guide
├── features.md                 # Features documentation
├── getting-started.md          # Getting started guide
└── ...                         # Additional documentation files

Best Practices for Generated Structure

  1. Keep Service Files Focused: Each service file should have a single responsibility.
  2. Organize Options: Group related options in nested option classes.
  3. Use Conditional Folders: Leverage conditional generation to keep the structure clean.
  4. Maintain Test Structure: Mirror the source structure in tests for easy navigation.
  5. Document Custom Handlers: If adding custom handlers or resilience policies, document them.

This structured approach ensures that your ConnectSoft API library is well-organized, easy to navigate, and ready for robust development and continuous integration.