Skip to content
  • templates
  • microservices
  • blueprints

Microservice Template

This document provides a technical deep-dive into the Microservice Template used by the ConnectSoft AI Software Factory. It is written for architects and engineers understanding template options, parameters, generated outputs, and how to extend templates.

The Microservice Template is the core template used by Engineering agents to generate production-ready microservices. It enforces Clean Architecture, DDD, event-driven patterns, and multi-tenant design while providing flexibility through parameters and extension points.

Important

All Factory-generated microservices follow this template structure. Consistency enables agents to generate code predictably and makes the codebase maintainable. The template is designed for multi-tenant SaaS applications following ConnectSoft's architectural principles.

Introduction

The ConnectSoft Microservice Template is a modular, scalable, and AI-integrated foundation for building cloud-native microservices. It empowers both humans and autonomous agents to generate, extend, and operate services that align with modern SaaS, DDD, Clean Architecture, and event-driven patterns — out of the box.

Whether you're building a single aggregate service or orchestrating thousands of AI-generated components, this template is the launchpad for fully traceable, observable, and secure backend systems.

Purpose

The ConnectSoft Microservice Template enables the rapid, scalable, and intelligent creation of production-grade microservices. It's designed for both:

  • 🤖 Autonomous agents in the ConnectSoft AI Software Factory
  • 👨‍💻 Human developers building enterprise, cloud-native solutions

The template scaffolds a multi-project solution that embodies:

  • ✅ Domain-Driven Design (DDD)
  • ✅ Clean Architecture principles
  • ✅ Event-Driven Messaging
  • ✅ Modular runtime options
  • ✅ Secure, observable, testable microservices

💡 It serves as the core automation blueprint for all ConnectSoft-generated services and is used at scale to create thousands of independently deployed modules.

Architectural Foundations

Paradigm Support
Domain-Driven Design ✅ Aggregates, Entities, Events, Repositories, Specs
Clean Architecture ✅ Structured layering: Domain → Application → Infrastructure → API
Event-Driven Architecture ✅ MassTransit / NServiceBus, pub-sub, outbox
Actor-Based Models ✅ Orleans, Dapr, Akka
Serverless Models ✅ Azure Functions
Modular APIs ✅ REST, gRPC, GraphQL, SignalR
AI Integration ✅ Semantic Kernel, OpenAI, Bot Framework
Infrastructure as Code ✅ Pulumi (Azure-first), Docker, Kubernetes

Composition & Solution Structure

Each generated service consists of 35+ modular projects, grouped by responsibility:

📦 Domain/
    ├── EntityModel/
    ├── DomainModel/
    └── DomainModel.Impl/

📦 Persistence/
    ├── PersistenceModel/
    ├── NHibernate / MongoDb/
    └── Migrations/

📦 Messaging/
    ├── MessagingModel/
    └── FlowModel.[NServiceBus|MassTransit]/

📦 ServiceModel/
    ├── RestApi / Grpc / GraphQL / SignalR / AzureFunction
    └── CoreWCF / ServiceFabric (optional)

📦 ActorModel/
    ├── Orleans / Dapr / Akka

📦 SchedulerModel/
    ├── Hangfire / Quartz

📦 AI/
    └── SemanticKernel/

📦 Bot/
    └── BotModel/

📦 Common/
    ├── Options/
    ├── Metrics/
    └── Core/

📦 Application/
    ├── ApplicationModel/
    └── Application (host)

📦 Infrastructure/
    ├── DockerCompose/
    └── InfrastructureModel/ (Pulumi)

📦 Testing/
    ├── UnitTests/
    ├── AcceptanceTests/
    └── ArchitectureTests/

📦 Architecture/
    ├── ArchitectureModel/
    └── DiagramAsCodeModel/

✅ Fully aligned to AI-assisted orchestration, CI/CD automation, and cross-platform deployments.

Generator & Automation Flow

flowchart TD
    VisionAgent --> ApplicationArchitectAgent
    ApplicationArchitectAgent --> MicroserviceGenerator
    MicroserviceGenerator -->|Uses| MicroserviceTemplate
    MicroserviceTemplate -->|Outputs| MultiProjectSolution
    MultiProjectSolution --> DevOpsPipeline
    DevOpsPipeline -->|Builds And Deploys| CloudService
Hold "Alt" / "Option" to enable pan & zoom

CLI Template Summary

The template is available as a reusable .NET template package, invoked via:

dotnet new connectsoft-microservice

Installation

dotnet new install ConnectSoft.MicroserviceTemplate::1.0.0

Generate a new service

dotnet new connectsoft-microservice \
  --AggregateRootName Order \
  --AggregateRootObjectId OrderId \
  --ServiceModelType RestApi \
  --PersistenceModelType NHibernate \
  --MessagingModelType NServiceBus \
  --UseOpenAI true \
  --UseSemanticKernel true

Included Best Practices

  • ✅ Strong layering and modularity
  • ✅ Isolation of service concerns
  • ✅ Environment-specific config injection
  • ✅ Secrets management, tenant guards, authentication
  • ✅ Observability-first (metrics, tracing, logging)
  • ✅ Test-first development, BDD, architecture validation

Template Goals and Design Principles

The Microservice Template is designed with these goals:

Alignment with Blueprint

  • Matches standard blueprint - Template implements the Microservice Standard Blueprint
  • Enforces structure - Template ensures all microservices follow the same layered structure
  • Consistent patterns - Same patterns applied across all generated services

Multi-Tenant SaaS Focus

  • Tenant isolation - Built-in tenant context handling at every layer
  • Multi-tenant data access - Repositories automatically filter by tenant
  • Tenant-aware APIs - APIs handle tenant context automatically

Composability and Extensibility

  • Modular structure - Each layer is independent and composable
  • Extension points - Clear places to add custom logic without breaking template
  • Template inheritance - Can extend base template for specialized variants

Agent Safety

  • Predictable structure - Agents know exactly what to generate
  • Validation built-in - Template validates inputs and outputs
  • Error prevention - Template prevents common mistakes

Template Parameters Overview

The template supports dozens of composable parameters to customize the generated solution:

Parameter Type Description
--AggregateRootName string Name of the aggregate (e.g., Order)
--AggregateRootObjectId string ID of the aggregate (e.g., OrderId)
--ServiceModelType choice RestApi, Grpc, GraphQL, SignalR, AzureFunction, None
--PersistenceModelType choice NHibernate, MongoDb, None
--MessagingModelType choice NServiceBus, MassTransit, None
--ActorModelType choice Orleans, Dapr, Akka, None
--SchedulerModelType choice Hangfire, Quartz, None
--NHibernateDialectType choice SqlServer, PostgreSQL, MySql
--NHibernateSecondLevelCacheType choice Redis, None
--MassTransitTransport choice SqlServer, RabbitMQ, AzureServiceBus
--NServiceBusTransport choice SqlServer, RabbitMQ
--UseSemanticKernel bool Adds Semantic Kernel orchestration
--UseOpenAI bool Enables OpenAI integrations
--UseMicrosoftBotBuilder bool Adds Microsoft Bot Framework entrypoints
--UseAuditNet bool Enables audit trail support
--HealthCheck, --HealthCheckUI bool Enables health endpoints and dashboards
--Swagger bool Enables Swagger / OpenAPI UI
--Logging choice Serilog, Log4Net, None
--DistributedCache choice InMemory, Redis, None
--OpenTelemetry bool Enables tracing, metrics, spans
--FeatureFlags bool Adds Microsoft.FeatureManagement
--FeatureFlagsProvider choice AppSettings, AzureAppConfiguration
--AdditionalConfigurationProvider choice AzureAppConfiguration, None
--Docker bool Adds Dockerfile, Docker Compose, and K8s manifests
--UsePulumi bool Adds Pulumi IaC infrastructure project
--UseApplicationInsights bool Azure App Insights support
--CORS bool Enables CORS middleware
--ResourceMonitoring bool Adds CPU/memory instrumentation
--HttpPort / --HttpsPort int Configurable port mapping
--DatabaseName string Primary DB name
--NServiceBusDatabaseName string NSB database name if selected

Conditional Inclusion

The template is designed with conditional project exclusion rules to optimize output:

  • 🚫 If --MessagingModelType is None, messaging folders and config are omitted
  • 🧠 If --UseSemanticKernel false, AI orchestration layers are skipped
  • 🐳 If --Docker false, no Dockerfile or Compose manifests are included
  • 🎭 If --ServiceModelType is None, no API projects are generated

This results in a minimal, purpose-driven solution, free of unused folders or dependencies.

AI-Driven Parameter Selection

When executed by ConnectSoft agents, parameters are automatically inferred from:

  • DomainModel.yaml → aggregate root and object ID
  • SystemArchitectureBlueprint → messaging, actor, service, scheduler selections
  • UseCaseBlueprint.json → triggers API, function, or message handler types
  • EditionMetadata → feature flag inclusion (e.g., AI, audit, bot)

Input Parameters (Factory API)

When using the Factory API, the template accepts these parameters:

Parameter Type Description Required
BoundedContextName string Name of the bounded context (e.g., "Invoice", "Billing") Yes
ServiceName string Name of the microservice (e.g., "InvoiceService", "BillingService") Yes
DomainEntities array List of domain entities with properties (e.g., [{name: "Invoice", properties: [...]}]) Yes
Aggregates array List of aggregates with entities (e.g., [{name: "InvoiceAggregate", entities: ["Invoice"]}]) Yes
UseCases array List of use cases (e.g., ["CreateInvoice", "UpdateInvoice", "GetInvoice"]) Yes
ApiEndpoints array List of API endpoints (e.g., [{method: "POST", path: "/invoices", useCase: "CreateInvoice"}]) Yes
PersistenceType enum Persistence technology: SqlServer, CosmosDb, PostgreSQL Yes
MessagingEnabled boolean Enable event-driven messaging (Service Bus integration) No (default: true)
EventSourcingEnabled boolean Enable event sourcing for aggregates No (default: false)
MultiTenantEnabled boolean Enable multi-tenant support No (default: true)
ObservabilityEnabled boolean Enable OpenTelemetry tracing and metrics No (default: true)
ApiType enum API type: REST, gRPC, Both No (default: REST)
TestFramework enum Test framework: xUnit, NUnit, MSTest No (default: xUnit)
TargetFramework string .NET target framework (e.g., "net8.0") No (default: net8.0)

Example Parameter Set:

{
  "BoundedContextName": "Invoice",
  "ServiceName": "InvoiceService",
  "DomainEntities": [
    {
      "name": "Invoice",
      "properties": [
        {"name": "Id", "type": "Guid"},
        {"name": "Amount", "type": "Money"},
        {"name": "Status", "type": "InvoiceStatus"}
      ]
    }
  ],
  "Aggregates": [
    {
      "name": "InvoiceAggregate",
      "entities": ["Invoice"]
    }
  ],
  "UseCases": ["CreateInvoice", "UpdateInvoice", "GetInvoice"],
  "ApiEndpoints": [
    {"method": "POST", "path": "/invoices", "useCase": "CreateInvoice"},
    {"method": "GET", "path": "/invoices/{id}", "useCase": "GetInvoice"}
  ],
  "PersistenceType": "CosmosDb",
  "MessagingEnabled": true,
  "MultiTenantEnabled": true
}

Generated Outputs

The template generates these outputs:

Projects

  • {ServiceName}.Api - API layer project (controllers, request/response models)
  • {ServiceName}.Application - Application layer project (use cases, DTOs, mappers)
  • {ServiceName}.Domain - Domain layer project (entities, value objects, domain events)
  • {ServiceName}.Infrastructure - Infrastructure layer project (repositories, messaging, external services)
  • {ServiceName}.Tests - Test project (unit, integration, acceptance tests)

Tests

  • Unit tests - Domain and application logic tests
  • Integration tests - API and infrastructure integration tests
  • Acceptance tests - End-to-end user story tests

Pipelines

  • azure-pipelines.yml - Azure DevOps CI/CD pipeline
  • Build stages - Compile, restore packages, run tests
  • Deploy stages - Deploy to dev, staging, production environments

Configuration Templates

  • appsettings.json - Application configuration template
  • appsettings.Development.json - Development environment config
  • appsettings.Production.json - Production environment config

Documentation

  • README.md - Service overview and setup instructions
  • architecture.md - Architecture documentation
  • ADR/ - Architecture Decision Records directory
  • OpenAPI spec - API documentation (Swagger/OpenAPI)

Infrastructure-as-Code

  • Bicep templates - Azure resource definitions
  • Kubernetes manifests - K8s deployment configs (if applicable)
  • Pulumi projects - Infrastructure-as-Code (if --UsePulumi enabled)

Output Example (when fully enabled)

ConnectSoft.MyService/
├── ApplicationModel/
├── Application/
├── DomainModel/
├── EntityModel/
├── MessagingModel/
├── FlowModel.MassTransit/
├── PersistenceModel/
├── PersistenceModel.NHibernate/
├── DatabaseModel.Migrations/
├── ServiceModel.RestApi/
├── SchedulerModel.Hangfire/
├── ActorModel.Orleans/
├── SemanticKernel/
├── BotModel/
├── DockerCompose/
├── InfrastructureModel/
└── UnitTests, AcceptanceTests, ArchitectureTests/

Generation Flow:

flowchart LR
    INPUT[Input Parameters] --> TEMPLATE[Template Engine]
    TEMPLATE --> PROJ[Projects]
    TEMPLATE --> TESTS[Tests]
    TEMPLATE --> PIPES[Pipelines]
    TEMPLATE --> CONFIG[Configuration]
    TEMPLATE --> DOCS[Documentation]
    TEMPLATE --> INFRA[Infrastructure]

    PROJ --> OUTPUT[Generated Artifacts]
    TESTS --> OUTPUT
    PIPES --> OUTPUT
    CONFIG --> OUTPUT
    DOCS --> OUTPUT
    INFRA --> OUTPUT

    style TEMPLATE fill:#2563EB,color:#fff
    style OUTPUT fill:#10B981,color:#fff
Hold "Alt" / "Option" to enable pan & zoom

Extension Points

The template provides clear extension points for adding custom logic:

Safe Extension Points

Where to add custom code:

  1. Domain Layer
  2. Add custom domain services in Domain/DomainServices/
  3. Add custom value objects in Domain/ValueObjects/
  4. Extend entities with custom methods (not properties that break template)

  5. Application Layer

  6. Add custom use cases in Application/UseCases/
  7. Add custom DTOs in Application/DTOs/
  8. Add custom mappers in Application/Mappers/

  9. Infrastructure Layer

  10. Add custom repositories in Infrastructure/Repositories/
  11. Add custom external service clients in Infrastructure/ExternalServices/
  12. Add custom messaging handlers in Infrastructure/Messaging/

  13. API Layer

  14. Add custom controllers in Api/Controllers/
  15. Add custom request/response models in Api/RequestModels/ or Api/ResponseModels/

What NOT to Touch

Avoid modifying:

  • Template-generated base classes - Base repository, base controller, etc.
  • Dependency injection setup - Program.cs, Startup.cs (unless adding new services)
  • Project file structure - Don't rename projects or move files between layers
  • Template-generated tests - Don't delete template tests, add new ones instead

Tip

When extending generated code, add new files rather than modifying template-generated files. This makes it easier to regenerate from template updates without losing custom code. Use partial classes or extension methods when you need to extend template-generated classes.

Extension Example

Scenario: Add custom invoice calculation logic.

Safe approach: 1. Create Domain/DomainServices/CustomInvoiceCalculationService.cs (new file) 2. Implement custom calculation logic 3. Register service in DI container 4. Use in use case

Avoid: - Modifying template-generated Invoice entity directly - Changing template-generated repository structure - Modifying base classes

Example: Creating a New Microservice

Scenario: Create a new "Notification" microservice for sending emails and push notifications.

Step 1: Define Parameters

{
  "BoundedContextName": "Notification",
  "ServiceName": "NotificationService",
  "DomainEntities": [
    {
      "name": "Notification",
      "properties": [
        {"name": "Id", "type": "Guid"},
        {"name": "Recipient", "type": "string"},
        {"name": "Message", "type": "string"},
        {"name": "Type", "type": "NotificationType"}
      ]
    }
  ],
  "Aggregates": [
    {
      "name": "NotificationAggregate",
      "entities": ["Notification"]
    }
  ],
  "UseCases": [
    "SendEmailNotification",
    "SendPushNotification",
    "GetNotificationStatus"
  ],
  "ApiEndpoints": [
    {"method": "POST", "path": "/notifications/email", "useCase": "SendEmailNotification"},
    {"method": "POST", "path": "/notifications/push", "useCase": "SendPushNotification"}
  ],
  "PersistenceType": "CosmosDb",
  "MessagingEnabled": true,
  "MultiTenantEnabled": true
}

Step 2: Template Generates

  • NotificationService.Domain - Notification entity, NotificationCreated event
  • NotificationService.Application - SendEmailNotificationUseCase, NotificationDto
  • NotificationService.Infrastructure - NotificationRepository, EmailServiceClient, PushServiceClient
  • NotificationService.Api - NotificationController with POST endpoints
  • NotificationService.Tests - Unit, integration, acceptance tests
  • CI/CD pipeline, infrastructure code, documentation

Step 3: Extend with Custom Logic

  • Add EmailTemplateService in Infrastructure/ExternalServices/
  • Add PushNotificationProvider in Infrastructure/ExternalServices/
  • Extend SendEmailNotificationUseCase to use custom email templates
  • Add custom tests for email and push notification scenarios

Result: Complete Notification microservice with custom email and push notification logic, following Clean Architecture and DDD principles.

Template Architecture

The Microservice Template is part of ConnectSoft's three-layer template architecture: