Skip to content

Documentation as Code in ConnectSoft Microservice Template

Purpose & Overview

Documentation as Code is a practice of treating documentation as version-controlled, automated, and continuously delivered artifacts that evolve alongside code. In the ConnectSoft Microservice Template, documentation is implemented as a first-class citizen using a comprehensive documentation-as-code stack that includes static site generation, architecture decision records, API documentation, and automated deployment pipelines.

Why Documentation as Code?

Documentation as Code offers several critical benefits:

  • Version Control: Documentation is versioned alongside code, enabling change tracking and history
  • Automation: Documentation is built and deployed automatically through CI/CD pipelines
  • Consistency: Same documentation generation process across all environments
  • Collaboration: Multiple developers can work on documentation without conflicts
  • Quality Gates: Documentation goes through the same validation and review processes as code
  • Living Documentation: Documentation stays in sync with code changes
  • Reproducibility: Documentation can be generated on-demand with consistent results
  • Integration: Documentation integrates with code, API documentation, and architecture decisions

Documentation as Code Philosophy

Documentation should be treated as code—versioned, tested, reviewed, and deployed automatically. This ensures documentation evolves in lock-step with code, passes through the same quality gates, and provides a single source of truth for all technical documentation.

Architecture Overview

Documentation Stack

The template uses a comprehensive documentation stack:

Documentation Sources
├── Markdown Files (Docs/)
│   ├── Architecture Guides
│   ├── Feature Documentation
│   ├── Getting Started Guides
│   └── API Documentation
├── Architecture Decision Records (ADRs)
│   └── log4brains (MADR format)
├── XML Documentation Comments
│   └── Swagger/OpenAPI Generation
└── Diagram as Code
    ├── Mermaid Diagrams
    └── Python Diagrams
Documentation Build
├── MkDocs (Static Site Generation)
├── log4brains (ADR Site Generation)
└── Swagger/OpenAPI (API Documentation)
Documentation Site
├── Static HTML Site (MkDocs Material)
├── ADR Site (Integrated)
└── API Documentation (Swagger UI)
Deployment
├── Azure Static Web Apps
├── On-Prem IIS
└── CI/CD Pipeline

Documentation Components

Component Purpose Technology
MkDocs Static site generation Python-based static site generator
Material for MkDocs Site theme and features Material Design theme for MkDocs
log4brains ADR management Node.js-based ADR tool
Mermaid Diagram markup Text-based diagram syntax
Python Diagrams Infrastructure diagrams Programmatic diagram generation
XML Comments API documentation .NET XML documentation
Swagger/OpenAPI API reference Swashbuckle/Swagger

MkDocs Static Site Generation

Overview

MkDocs is a fast, simple, and downright gorgeous static site generator for building project documentation. Documentation source files are written in Markdown and configured with a single YAML configuration file.

Installation

Prerequisites: - Python 3.7+ - pip (Python package manager)

Install MkDocs and Material Theme:

pip install mkdocs-material

Or via requirements file:

pip install -r requirements.txt

Configuration

mkdocs.yml:

# https://github.com/squidfunk/mkdocs-material/blob/master/mkdocs.yml

# Project information
site_name: ConnectSoft.MicroserviceTemplate
site_url: https://dev.azure.com/dmitrykhaymov/ConnectSoft/_git/ConnectSoft.MicroserviceTemplate
site_description: >-
    **TODO:** Provide a concise yet informative description outlining the primary functionality and purpose of the `ConnectSoft.MicroserviceTemplate` microservice.
site_author: ConnectSoft.MicroserviceTemplate Developers

# Repository information
repo_name: ConnectSoft.MicroserviceTemplate
repo_url: https://dev.azure.com/dmitrykhaymov/ConnectSoft/_git/ConnectSoft.MicroserviceTemplate

# Copyright
copyright: Copyright © 2024 - 2025 ConnectSoft

docs_dir: Docs

# Theme configuration
theme:
  name: material
  features:
    - announce.dismiss
    - content.action.edit
    - content.action.view
    - content.code.annotate
    - content.code.copy
    - content.tooltips
    - navigation.footer
    - navigation.indexes
    - navigation.sections
    - navigation.tabs
    - navigation.top
    - navigation.tracking
    - search.highlight
    - search.share
    - search.suggest
    - toc.follow
  palette:
    - media: "(prefers-color-scheme)"
      scheme: default
      primary: indigo
      accent: indigo
    - media: "(prefers-color-scheme: dark)"
      scheme: slate
      primary: black
      accent: indigo
  font:
    text: Roboto
    code: Roboto Mono
  favicon: assets/logo3.webp

Markdown Extensions

Extended Features:

markdown_extensions:
  - abbr
  - admonition
  - attr_list
  - def_list
  - footnotes
  - md_in_html
  - toc:
      permalink: true
  - pymdownx.arithmatex:
      generic: true
  - pymdownx.betterem:
      smart_enable: all
  - pymdownx.caret
  - pymdownx.details
  - pymdownx.emoji:
      emoji_generator: !!python/name:material.extensions.emoji.to_svg
      emoji_index: !!python/name:material.extensions.emoji.twemoji
  - pymdownx.highlight:
      anchor_linenums: true
      line_spans: __span
      pygments_lang_class: true
  - pymdownx.inlinehilite
  - pymdownx.keys
  - pymdownx.magiclink
  - pymdownx.mark
  - pymdownx.smartsymbols
  - pymdownx.snippets:
      auto_append:
        - includes/mkdocs.md
  - pymdownx.superfences:
      custom_fences:
        - name: mermaid
          class: mermaid
          format: !!python/name:pymdownx.superfences.fence_code_format
  - pymdownx.tabbed:
      alternate_style: true
      combine_header_slug: true
  - pymdownx.tasklist:
      custom_checkbox: true
  - pymdownx.tilde

Defining Navigation:

nav:
  - Home: Index.md
  - Public:
      - Foundations:
         - DDD In Microservice Template: public/foundations/ddd.md
         - Clean Architecture: public/foundations/clean-architecture.md
  - Overview:
      - Overview: Overview.md
      - ConnectSoft.MicroserviceTemplate Canvas: ConnectSoft.MicroserviceTemplate Canvas.md
      - API Reference: API Reference.md
  - Architecture:
      - Architecture: Architecture.md
  - Guides:
      - Getting Started: Getting Started.md
      - Installation: Installation.md
      - Troubleshooting: Troubleshooting.md

Plugins

Search and Exclusions:

plugins:
  - search:
      separator: '[\s\u200b\-_,:!=\[\]()"`/]+|\.(?!\d)|&[lg]t;|(?!\b)(?=[A-Z][a-z])'
  - exclude:
      glob:
        - "Diagrams/**"
        - "Build.md"
        - "Template Development TODO.md"

Building Documentation

Local Development:

# Start development server (auto-reload on changes)
mkdocs serve

# Access at http://127.0.0.1:8000

Build Static Site:

# Build static site
mkdocs build

# Output in site/ directory

Strict Build (Validation):

# Build with strict validation (fails on errors)
mkdocs build --strict

Validation Checks: - Broken links - Missing files - Invalid Markdown syntax - Missing assets (images, etc.)

Architecture Decision Records (ADRs)

Overview

Architecture Decision Records (ADRs) are documents that capture important architectural decisions made along with their context and consequences. The template uses log4brains to manage ADRs in a structured, searchable format.

log4brains Configuration

Configuration File (.log4brains.yml):

project:
  name: ConnectSoft Microservice Documentation Template
  tz: UTC
  adrFolder: docs/adr

Package.json Scripts:

{
  "scripts": {
    "adr:preview": "log4brains preview",
    "adr:new": "log4brains adr new",
    "adr:build": "log4brains build --basePath /adr"
  }
}

Creating ADRs

Interactive Creation:

npm run adr:new

Manual Creation:

# ADR-0002: Use OpenTelemetry for Distributed Tracing

* Status: accepted
* Deciders: ConnectSoft Team
* Date: 2025-01-15

## Context and Problem Statement

We need a standardized approach to distributed tracing across microservices. Multiple tracing solutions exist, each with different integration requirements and capabilities.

## Decision Drivers

* Need for standardized tracing format
* Multi-vendor observability support
* Integration with existing .NET ecosystem
* Open-source, vendor-neutral approach

## Considered Options

* Application Insights only
* OpenTelemetry
* Custom tracing solution

## Decision Outcome

Chosen option: "OpenTelemetry", because it provides:

* Vendor-neutral, open-source standard
* Wide ecosystem support
* Integration with multiple backends
* Active community and development

### Positive Consequences

* Standardized tracing across services
* Vendor flexibility
* Rich instrumentation ecosystem
* Future-proof approach

### Negative Consequences

* Additional configuration complexity
* Learning curve for team members
* Need for OpenTelemetry Collector in some setups

## Links

* [OpenTelemetry Documentation](https://opentelemetry.io/docs/)
* [OpenTelemetry .NET](https://github.com/open-telemetry/opentelemetry-dotnet)

ADR Structure (MADR Format)

Required Sections:

  1. Header: Status, Deciders, Date
  2. Context and Problem Statement: What problem are we solving?
  3. Decision Drivers: Factors influencing the decision
  4. Considered Options: Alternatives evaluated
  5. Decision Outcome: Chosen option and rationale
  6. Consequences: Positive and negative impacts
  7. Links: Related documentation and resources

Status Values: - proposed: Under consideration - accepted: Decision made and adopted - deprecated: Decision superseded or obsolete - superseded: Replaced by another ADR

Viewing ADRs

Local Preview:

npm run adr:preview
# Access at http://localhost:4004

Build ADR Site:

npm run adr:build
# Output in .log4brains/out/

ADR Integration with MkDocs

CI/CD Integration:

# Build ADRs
- script: |
    npm install -g log4brains
    npm run adr:build
  displayName: 'Build ADRs with log4brains'

# Merge into MkDocs site
- script: |
    mkdir -p $(siteDirectory)/adr
    cp -r .log4brains/out/* $(siteDirectory)/adr/
  displayName: 'Merge ADRs into MkDocs site'

Result: ADRs are accessible at /adr path in the documentation site.

XML Documentation Comments

Overview

XML Documentation Comments provide inline API documentation that is extracted during build and used to generate comprehensive API reference documentation via Swagger/OpenAPI.

Enabling XML Documentation

Project Configuration:

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

Directory.Build.props (applied to all projects):

<PropertyGroup>
  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</PropertyGroup>

Writing XML Comments

Class Documentation:

/// <summary>
/// Processes microservice aggregate root operations.
/// </summary>
/// <remarks>
/// This processor handles creation, update, and deletion of aggregate roots
/// following Domain-Driven Design principles.
/// </remarks>
public class MicroserviceAggregateRootsProcessor : IMicroserviceAggregateRootsProcessor
{
    /// <summary>
    /// Creates a new microservice aggregate root.
    /// </summary>
    /// <param name="input">The input containing aggregate root creation details.</param>
    /// <param name="cancellationToken">Cancellation token to cancel the operation.</param>
    /// <returns>The created aggregate root.</returns>
    /// <exception cref="ValidationException">Thrown when input validation fails.</exception>
    /// <exception cref="DomainModelException">Thrown when business rules are violated.</exception>
    public async Task<IMicroserviceAggregateRoot> CreateMicroserviceAggregateRootAsync(
        CreateMicroserviceAggregateRootInput input,
        CancellationToken cancellationToken)
    {
        // Implementation
    }
}

Property Documentation:

/// <summary>
/// Gets or sets the unique identifier for the aggregate root.
/// </summary>
/// <value>
/// A <see cref="Guid"/> that uniquely identifies the aggregate root.
/// </value>
public Guid ObjectId { get; set; }

Parameter Documentation:

/// <param name="objectId">The unique identifier of the aggregate root to retrieve.</param>
/// <param name="cancellationToken">Cancellation token to cancel the operation.</param>

Exception Documentation:

/// <exception cref="ArgumentException">Thrown when <paramref name="objectId"/> is empty.</exception>
/// <exception cref="NotFoundException">Thrown when the aggregate root is not found.</exception>

Swagger Integration

XML Comments in Swagger:

// SwaggerExtensions.cs
internal static IServiceCollection AddSwagger(this IServiceCollection services)
{
    if (OptionsExtensions.SwaggerOptions.EnableSwagger)
    {
        string serviceModelXmlCommentsFilePath = null;
        string apiModelXmlCommentsFilePath = null;

        // Find XML documentation files
        string[] files = Directory.GetFiles(
            AppDomain.CurrentDomain.BaseDirectory, 
            searchPattern: "ConnectSoft.MicroserviceTemplate.ServiceModel.xml", 
            searchOption: SearchOption.AllDirectories);
        if (files != null && files.Length == 1)
        {
            serviceModelXmlCommentsFilePath = files[0];
        }

        files = Directory.GetFiles(
            AppDomain.CurrentDomain.BaseDirectory, 
            searchPattern: "ConnectSoft.MicroserviceTemplate.ServiceModel.RestApi.xml", 
            searchOption: SearchOption.AllDirectories);
        if (files != null && files.Length == 1)
        {
            apiModelXmlCommentsFilePath = files[0];
        }

        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo 
            { 
                Title = "ConnectSoft.MicroserviceTemplate's microservice back-end API", 
                Version = "v1" 
            });

            if (!string.IsNullOrEmpty(serviceModelXmlCommentsFilePath))
            {
                c.IncludeXmlComments(serviceModelXmlCommentsFilePath);
            }

            if (!string.IsNullOrEmpty(apiModelXmlCommentsFilePath))
            {
                c.IncludeXmlComments(apiModelXmlCommentsFilePath);
            }

            c.EnableAnnotations(enableAnnotationsForInheritance: true, enableAnnotationsForPolymorphism: true);
            c.UseAllOfForInheritance();
        });
    }

    return services;
}

Result: Swagger UI displays XML comments as API documentation.

Documentation Structure

Directory Layout

Docs/
├── Index.md                          # Home page
├── Overview.md                       # Overview documentation
├── Getting Started.md                # Getting started guide
├── Installation.md                   # Installation instructions
├── Architecture.md                   # Architecture documentation
├── Configuration.md                  # Configuration guide
├── Troubleshooting.md                # Troubleshooting guide
├── public/
│   └── foundations/                  # Foundation documentation
│       ├── ddd.md
│       ├── clean-architecture.md
│       ├── logging.md
│       ├── distributed-tracing.md
│       └── ... (85+ foundation docs)
├── adr/                              # Architecture Decision Records
│   ├── adr-0001-use-log4brains-for-architecture-decision-records.md
│   └── ... (more ADRs)
├── Diagrams/                         # Diagram source files
│   ├── Solution Structure Graph.mmd
│   └── Use Cases.mmd
└── assets/                           # Images and assets
    ├── logo1.webp
    ├── logo2.webp
    └── logo3.webp

Content Organization

Foundations (public/foundations/): - Core concepts and patterns - Framework integrations - Best practices - Reference documentation

Guides: - Getting started - Installation - Configuration - Troubleshooting

Features: - Feature-specific documentation - Use cases - Examples

Modeling: - Entity Model - Domain Model - Service Model - Persistence Model - Actor Model - Scheduler Model

CI/CD Integration

Documentation Pipeline

Pipeline File: azure-pipelines-documentation.yml

Trigger:

trigger:
  branches:
    include:
    - master
  paths:
    include:
    - README.md
    - Docs/*
    - Images/**
    - azure-pipelines-documentation.yml
    - mkdocs.yml

Build Stage:

- stage: 'BUILD_DOCS_SITE'
  displayName: 'Build Documentation Site for ConnectSoft.MicroserviceTemplate'
  pool:
      vmImage: 'ubuntu-latest'
  jobs:
    - job: 'GENERATE_DOCS_SITE'
      steps:
        # Build MkDocs site
        - template: generate/generate-microservice-documentation-steps.yaml@templates
          parameters:
             artifactName: $(artifactName)
             siteDirectory: $(siteDirectory)

        # Setup Node.js for log4brains
        - task: NodeTool@0
          displayName: 'Setup Node.js LTS'
          inputs:
            versionSpec: '18.x'

        # Install log4brains globally
        - script: |
            npm install -g log4brains
          displayName: 'Install log4brains'

        # Build ADRs
        - script: |
            npm run adr:build
          displayName: 'Build ADRs with log4brains'

        # Merge ADR output into MkDocs site
        - script: |
            mkdir -p $(siteDirectory)/adr
            cp -r .log4brains/out/* $(siteDirectory)/adr/
            echo "ADR files merged into site/adr:"
            ls -la $(siteDirectory)/adr/
          displayName: 'Merge ADRs into MkDocs site'

        # Publish artifact
        - task: PublishPipelineArtifact@1
          inputs:
            targetPath: $(siteDirectory)
            artifactName: $(artifactName)
            publishLocation: 'pipeline'
          displayName: 'Publish merged site artifact'

Deploy Stage:

- stage: 'DEPLOY_DOCS_SITE_ONPREM'
  displayName: 'Deploy Documentation Site for ConnectSoft.MicroserviceTemplate'
  dependsOn: 'BUILD_DOCS_SITE'
  condition: succeeded()
  pool: Default
  jobs:
    - job: waitForApproval
      displayName: Wait for approval
      pool: server
      timeoutInMinutes: 4320
      steps:   
        - task: ManualValidation@0
          timeoutInMinutes: 4320
          inputs:
            notifyUsers: $(notifyUsersList)
            instructions: 'Please review the build configuration of ConnectSoft.MicroserviceTemplate Documentation site and resume IIS release to Tests'
            onTimeout: 'reject'
    - job: 'Docs_Site_Deploy_To_IIS'
      displayName: 'Deploy ConnectSoft.MicroserviceTemplate Documentation site To IIS - Tests'
      dependsOn: waitForApproval
      condition: succeeded()
      steps:
        - template: deploy/deploy-static-site-to-iis.yaml@templates
          parameters:
             artifactName: $(artifactName)
             microserviceName: 'ConnectSoft.MicroserviceTemplate'
             applicationPoolName: 'ConnectSoft.MicroserviceTemplate.Docs'
             applicationName: 'ConnectSoft.MicroserviceTemplate.Docs'
             parentWebsiteName: 'Default Web Site'

Build Process

Steps:

  1. Build MkDocs Site: Generates static HTML from Markdown
  2. Build ADRs: Generates ADR site using log4brains
  3. Merge ADRs: Integrates ADR output into MkDocs site
  4. Publish Artifact: Creates build artifact for deployment
  5. Deploy: Deploys to target environment (IIS, Azure Static Web Apps)

Validation

Strict Build:

mkdocs build --strict

Validation Checks: - Broken internal links - Missing files - Invalid Markdown syntax - Missing referenced assets - Invalid navigation structure

Local Development

Preview Documentation

MkDocs Preview:

# Start development server
mkdocs serve

# Access at http://127.0.0.1:8000
# Auto-reloads on file changes

ADR Preview:

# Preview ADR site
npm run adr:preview

# Access at http://localhost:4004

Creating New Documentation

Add New Page:

  1. Create Markdown file in Docs/ directory
  2. Add entry to mkdocs.yml navigation
  3. Preview locally with mkdocs serve
  4. Commit and push changes

Example:

# New Feature Documentation

## Overview

This feature provides...

## Usage

\```csharp
// Example code
\```

Update Navigation:

nav:
  - Features:
      - New Feature: NewFeature.md

Best Practices

Do's

  1. Keep Documentation Up to Date

    # ✅ GOOD - Update docs with code changes
    # When adding a new feature, update documentation immediately
    

  2. Use Consistent Formatting

    # ✅ GOOD - Consistent heading structure
    ## Overview
    ## Architecture
    ## Usage
    ## Examples
    

  3. Include Code Examples

    # ✅ GOOD - Practical examples
    ```csharp
    // Example code
    var service = new MyService();
    
    ```

  4. Document Decisions

    # ✅ GOOD - Create ADR for significant decisions
    # ADR-0005: Use Redis for distributed caching
    

  5. Use Cross-References

    # ✅ GOOD - Link to related documentation
    See [Configuration](../configuration-feature-management/configuration.md) for setup details.
    See [Logging](./logging.md) for logging configuration.
    

  6. Validate Before Committing

    # ✅ GOOD - Validate locally
    mkdocs build --strict
    npm run adr:build
    

  7. Use Admonitions for Important Information

    !!! warning "Important"
        This configuration requires a restart of the service.
    
    !!! info "Note"
        This feature is available in version 1.0.0 and later.
    

Don'ts

  1. Don't Commit Generated Files

    # ❌ BAD - Don't commit site/ directory
    git add site/
    
    # ✅ GOOD - Generated files are build artifacts
    # Add site/ to .gitignore
    

  2. Don't Use Hardcoded URLs

    # ❌ BAD - Hardcoded URLs
    See https://dev.azure.com/.../wiki/...
    
    # ✅ GOOD - Relative paths
    See [Configuration](../configuration-feature-management/configuration.md)
    

  3. Don't Skip ADRs for Significant Decisions

    # ❌ BAD - No ADR for major architectural change
    # Just a comment in code: "We chose Redis for caching"
    
    # ✅ GOOD - Formal ADR
    # ADR-0005: Use Redis for distributed caching
    

  4. Don't Duplicate Information

    # ❌ BAD - Duplicate content across multiple files
    # Same configuration example in 5 different files
    
    # ✅ GOOD - Single source of truth with cross-references
    # See [Configuration](../configuration-feature-management/configuration.md) for details.
    

  5. Don't Use Ambiguous Language

    # ❌ BAD - Vague descriptions
    The service does things.
    
    # ✅ GOOD - Specific descriptions
    The service processes orders by validating inventory, processing payments, and updating shipping status.
    

  6. Don't Forget to Update Navigation

    # ❌ BAD - New page not in navigation
    # Created NewFeature.md but forgot to add to nav
    
    # ✅ GOOD - Update navigation
    nav:
      - Features:
          - New Feature: NewFeature.md
    

Markdown Features

Admonitions

Info Boxes:

!!! info "Information"
    This is an informational note.

!!! warning "Warning"
    This is a warning message.

!!! danger "Danger"
    This is a danger message.

!!! tip "Tip"
    This is a helpful tip.

!!! note "Note"
    This is a note.

Code Blocks

Syntax Highlighting:

```csharp
public class MyService
{
    public void DoWork()
    {
        // Code here
    }
}
```

Line Numbers:

```csharp
:1:5:MyService.cs
public class MyService
{
    public void DoWork()
    {
        // Code here
    }
}
```

Mermaid Diagrams

Embedded Diagrams:

```mermaid
flowchart TD
    A[Start] --> B[Process]
    B --> C[End]
```

See Diagram as Code for detailed information.

Tables

Markdown Tables:

| Feature | Status | Notes |
|---------|--------|-------|
| REST API | ✅ | Fully implemented |
| gRPC | ✅ | Fully implemented |
| GraphQL | 🚧 | In progress |

Tabs

Tabbed Content:

=== "C#"
    ```csharp
    var service = new MyService();
    ```

=== "JavaScript"
    ```javascript
    const service = new MyService();
    ```

Task Lists

Checkboxes:

- [x] Completed task
- [ ] Pending task
- [ ] Another task

Documentation Workflow

Authoring Workflow

Branching Model:

main/master
feature/docs-update
    ├── Update Markdown files
    ├── Create/update ADRs (if needed)
    ├── Update navigation
    └── Preview locally
Pull Request
    ├── CI builds documentation
    ├── Preview site generated
    └── Reviewers validate
Merge to main
    ├── Documentation deployed
    └── Available in production

Workflow Steps:

  1. Create Feature Branch: git checkout -b feature/docs-update
  2. Edit Documentation: Update Markdown files
  3. Preview Locally: mkdocs serve
  4. Validate: mkdocs build --strict
  5. Commit: git commit -m "docs: update configuration guide"
  6. Push and Create PR: Push to remote, create pull request
  7. Review: Team reviews documentation
  8. Merge: Merge to main triggers deployment

ADR Workflow

Creating ADRs:

  1. Identify Decision: Architectural decision needs to be documented
  2. Create ADR: npm run adr:new
  3. Fill Template: Complete MADR template
  4. Review: Team reviews ADR
  5. Accept: Update status to accepted
  6. Commit: Commit ADR to repository

Updating ADRs:

  • Status Changes: Update status when decision evolves
  • Superseding: Create new ADR and mark old one as superseded
  • Deprecating: Mark as deprecated when no longer relevant

Deployment

Deployment Targets

Environment Platform Authentication Notes
Test On-Prem IIS None Manual approval required
Production Azure Static Web Apps Enforced Auto-deployed on merge
Preview PR environment Optional Auto-generated per PR

On-Prem IIS Deployment

Configuration:

- template: deploy/deploy-static-site-to-iis.yaml@templates
  parameters:
     artifactName: $(artifactName)
     microserviceName: 'ConnectSoft.MicroserviceTemplate'
     applicationPoolName: 'ConnectSoft.MicroserviceTemplate.Docs'
     applicationName: 'ConnectSoft.MicroserviceTemplate.Docs'
     parentWebsiteName: 'Default Web Site'

Azure Static Web Apps

Configuration:

- task: AzureStaticWebApp@0
  inputs:
    app_location: "site"
    skip_app_build: true
    api_location: ""
    output_location: ""

Quality Assurance

Validation

Link Checking:

# Check for broken links
mkdocs build --strict

Markdown Linting:

# Optional: Use markdownlint
npx markdownlint "docs/**/*.md"

ADR Validation:

  • Sequential numbering
  • Correct front-matter format
  • Required sections present
  • Status values valid

Review Process

Documentation Review Checklist:

  • All links work correctly
  • Code examples are accurate
  • Diagrams render correctly
  • Navigation is updated
  • ADRs are created for significant decisions
  • Cross-references are correct
  • Formatting is consistent
  • No typos or grammatical errors

Integration with Code

Code-to-Documentation Sync

Automatic API Documentation: - XML comments extracted during build - Swagger/OpenAPI generated automatically - API reference stays in sync with code

Documentation Generation: - Diagrams generated from code - Architecture diagrams from project structure - Solution structure from actual projects

Version Alignment

Documentation Versioning:

extra:
  version:
    provider: mike

Versioned URLs: - /v1.3/ - Specific version - /v1.4/ - Latest version - /latest/ - Always latest

Troubleshooting

Issue: MkDocs Build Fails

Symptoms: mkdocs build command fails with errors.

Solutions: 1. Check Markdown syntax errors 2. Verify all referenced files exist 3. Check navigation structure in mkdocs.yml 4. Verify image paths are correct 5. Check for broken internal links 6. Review extension configuration

Issue: ADRs Not Building

Symptoms: ADR build fails or ADRs not appearing in site.

Solutions: 1. Verify Node.js is installed: node --version 2. Check log4brains is installed: npm list -g log4brains 3. Verify .log4brains.yml configuration 4. Check ADR file format (MADR template) 5. Verify ADR folder path is correct 6. Check for ADR numbering conflicts

Issue: XML Comments Not Appearing in Swagger

Symptoms: XML comments not showing in Swagger UI.

Solutions: 1. Verify GenerateDocumentationFile is true 2. Check XML file is generated in build output 3. Verify XML file path in Swagger configuration 4. Check XML file is included in deployment 5. Verify XML comments syntax is correct 6. Check file search pattern matches actual file name

Symptoms: Links to other documentation pages don't work.

Solutions: 1. Use mkdocs build --strict to find broken links 2. Verify file paths are correct (case-sensitive) 3. Check navigation structure matches file locations 4. Use relative paths, not absolute URLs 5. Verify referenced files exist 6. Check for typos in file names

Advanced Patterns

Custom Plugins

MkDocs Plugins:

# Custom plugin example
from mkdocs.plugins import BasePlugin

class MyPlugin(BasePlugin):
    def on_page_markdown(self, markdown, **kwargs):
        # Transform markdown
        return markdown

Documentation Snippets

Reusable Snippets:

# mkdocs.yml
markdown_extensions:
  - pymdownx.snippets:
      auto_append:
        - includes/mkdocs.md

includes/mkdocs.md:

---
Note: This content is automatically appended to all pages.
---

Multi-Language Documentation

Language Switching:

theme:
  language: en
  features:
    - content.code.copy

plugins:
  - i18n:
      default_language: en
      languages:
        en: English
        es: Español
        fr: Français

Summary

Documentation as Code in the ConnectSoft Microservice Template provides:

  • Version Control: Documentation versioned alongside code
  • Automation: Automated build and deployment through CI/CD
  • MkDocs Integration: Professional static site generation
  • ADR Management: Structured architecture decision records
  • API Documentation: XML comments for Swagger/OpenAPI
  • Diagram Integration: Mermaid and Python diagrams
  • Quality Gates: Validation and review processes
  • Multi-Format Support: Markdown, ADRs, XML comments, diagrams

By following these patterns, teams can:

  • Maintain Accurate Documentation: Documentation stays in sync with code
  • Collaborate Effectively: Multiple developers can work on documentation
  • Automate Delivery: Documentation deployed automatically
  • Track Decisions: ADRs provide decision history
  • Generate API Docs: Automatic API documentation from code
  • Ensure Quality: Validation and review processes
  • Version Documentation: Documentation aligned with code versions

Documentation as Code transforms documentation from a static, often-outdated artifact into a living, version-controlled, continuously delivered resource that evolves with the codebase, ensuring teams always have accurate, up-to-date documentation.