Skip to content

๐Ÿงฉ ConnectSoft Microservice Template

๐Ÿš€ 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

Command Description
dotnet new connectsoft-microservice Instantiates a new microservice
--AggregateRootName The name of the main entity (e.g., Order)
--PersistenceModelType NHibernate, MongoDb, or None
--MessagingModelType NServiceBus, MassTransit, or None
--ServiceModelType RestApi, Grpc, GraphQL, SignalR, AzureFunction
--ActorModelType Orleans, Dapr, Akka, or None
--SchedulerModelType Hangfire, Quartz, or None
--UseSemanticKernel Adds AI orchestration capabilities
--UseOpenAI Enables OpenAI integration
--Docker, --UsePulumi Infrastructure and deployment options
--UseMicrosoftBotBuilder Adds Microsoft Bot Framework integration
--Swagger, --HealthCheck, --CORS, --FeatureFlags Enables specific cross-cutting features

๐Ÿ”„ All CLI options are agent-compatible and can be dynamically toggled based on use case requirements.


๐Ÿงช 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

โœ… Summary

The ConnectSoft Microservice Template is the launchpad for building composable SaaS, intelligent backend systems, and domain-specific modules with:

  • Predictable structure
  • AI extensibility
  • Full observability
  • CI/CD integration
  • Cloud-native runtime support

โš™๏ธ Template Generation and Parameters

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

dotnet new connectsoft-microservice

It is designed to support:

  • ๐Ÿ” Human developers (manual CLI generation)
  • ๐Ÿค– ConnectSoft AI Agents (automated generation)
  • ๐Ÿงฑ Highly configurable options to generate only the necessary features

โœ… The template is parameterized and modular, allowing each concern (e.g., messaging, actors, service models) to be toggled on or off at generation time.


๐Ÿงฉ Installation and Usage

๐Ÿ”ง Install from NuGet / Azure DevOps Feed

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

๐Ÿ“Œ Template Parameters Overview

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)

๐Ÿ“ฆ 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/

โœ… Summary

  • Supports dozens of composable parameters
  • Output is modular, minimal, and runtime-configurable
  • Fully aligned with agentic generation and manual CLI workflows
  • Enables clean automation, feature toggling, and extension-by-design

๐Ÿงฑ Supported Architectures and Runtime Models

The ConnectSoft Microservice Template is engineered to support multiple architectural styles and execution runtimes. This makes it suitable for a wide range of modern SaaS, enterprise, and AI-powered systems โ€” from domain-oriented REST services to actor-based real-time systems, background jobs, and serverless tasks.


๐Ÿงฑ Clean Architecture

The solution is built with strict separation of concerns across well-defined layers:

flowchart TD
  UI[ServiceModel Layer - REST/gRPC/GraphQL] --> Domain[DomainModel + EntityModel]
  Domain --> Infra[Infrastructure + Persistence]
Hold "Alt" / "Option" to enable pan & zoom
Layer Role
DomainModel Encapsulates core business logic, aggregates, and events
ApplicationModel Coordinates use cases, handles cross-cutting concerns
ServiceModel Interface adapters: REST, gRPC, GraphQL, SignalR
PersistenceModel Abstract data access (SQL, NoSQL)
PersistenceModel.[NHibernate/MongoDB] Real implementations (e.g., NHibernate, MongoDB, Dapper)

โœ… The domain model never references infrastructure such as(NHibernate/MongoDB), enforcing inward dependency flow.


๐Ÿง  Domain-Driven Design (DDD)

The template is deeply aligned with DDD tactical patterns, supporting:

  • โœ… Aggregate roots, entities and domain events
  • โœ… Value objects and enumerations
  • โœ… Domain services and factories
  • โœ… Ubiquitous language and modeling boundaries
  • โœ… Specifications and queries

๐Ÿ”„ Domain models are split across:

Project Role
EntityModel Aggregate roots, entities, value objects
DomainModel Interfaces for domain services and events
DomainModel.Impl Implementations and validation logic

๐Ÿ•ธ๏ธ Event-Driven Architecture (EDA)

Supports both MassTransit and NServiceBus for:

  • Domain โ†’ Integration event publishing
  • Pub-sub with external systems
  • Outbox pattern and retries
  • Saga orchestration and stateful flows
Transport Saga Engine Persistence Options
MassTransit Yes NHibernate, MongoDB, CosmosDB, Dapper
NServiceBus Yes SQL, MongoDB, CosmosDB

๐Ÿ“ฆ Messaging is modular via:

  • MessagingModel
  • FlowModel.MassTransit or FlowModel.NServiceBus

๐Ÿง  Actor Model Support

Supports virtual actor systems for distributed, stateful logic.

Framework Project
Orleans ActorModel.Orleans
Dapr ActorModel.Dapr
Akka.NET ActorModel.Akka

Actors are fully isolated and support telemetry, AI integration, and Saga handoffs.


๐Ÿ”„ Background Execution Models

Job-based, long-running, or schedule-triggered workloads are supported via:

Runtime Project
Hangfire SchedulerModel.Hangfire
Quartz SchedulerModel.Quartz
Azure Functions ServiceModel.AzureFunction

๐Ÿง  All jobs can emit domain events or call use cases directly.


๐ŸŒ API Surface Options

The template supports 6 different service exposure modes, each swappable via parameters:

API Type Project
REST ServiceModel.RestApi
gRPC ServiceModel.Grpc
GraphQL ServiceModel.GraphQL
SignalR ServiceModel.SignalR
Azure Functions ServiceModel.AzureFunction
CoreWCF / Service Fabric Optional add-ons
  • ๐Ÿ“œ Swagger and ProblemDetails are integrated for REST.
  • ๐Ÿงฌ Proto files are auto-generated for gRPC.

๐Ÿ“ฆ Multi-Host Runtime Models

The host application can run with multiple entry modes:

Mode Purpose
REST API Host Primary HTTP interface
gRPC Server High-performance structured messaging
SignalR Hub Real-time pub/sub with browser or mobile clients
Background Worker Polling, sagas, job orchestration
Azure Functions Host Serverless, event-driven executions
Orleans / Dapr Host Actor-based compute node

โœ… All hosts share the same domain and infrastructure model.


๐Ÿง  Semantic Kernel AI Support

If --UseSemanticKernel is enabled:

  • AI Skills are added to the application pipeline
  • OpenAI, Azure OpenAI, Ollama, HuggingFace connectors supported
  • Optional plugins: OpenAPI, Microsoft Graph, Memory, Web, Document, gRPC
  • Integrated actor flows and planner orchestration supported

๐Ÿง  Generated microservices become agent-compatible and language-aware.


โœ… Summary

The ConnectSoft Microservice Template supports:

  • Rich architectural layering (Clean, DDD)
  • Modular exposure (REST/gRPC/GraphQL/SignalR)
  • Background and serverless compute
  • Messaging, eventing, actors, and jobs
  • AI orchestration with optional plugins
  • Runtime flexibility: multi-host, multi-db, multi-cloud

๐Ÿ—๏ธ Solution Structure and Project Breakdown

The ConnectSoft Microservice Template generates a multi-project solution, organized to enforce:

  • ๐Ÿ” Separation of concerns
  • ๐Ÿ”’ Bounded context isolation
  • ๐Ÿงฉ Feature composability
  • ๐Ÿ”Œ Optional runtime modules

This section outlines the solution structure, including libraries, host apps, integration models, testing, and diagrams.


๐Ÿ—‚๏ธ Tree-Based Structure (Simplified)

ConnectSoft.MyService/
โ”œโ”€โ”€ Common/
โ”‚   โ”œโ”€โ”€ MyService/
โ”‚   โ”œโ”€โ”€ MyService.Options/
โ”‚   โ””โ”€โ”€ MyService.Metrics/
โ”œโ”€โ”€ Domain/
โ”‚   โ”œโ”€โ”€ MyService.EntityModel/
โ”‚   โ”œโ”€โ”€ MyService.DomainModel/
โ”‚   โ””โ”€โ”€ MyService.DomainModel.Impl/
โ”œโ”€โ”€ Persistence/
โ”‚   โ”œโ”€โ”€ MyService.PersistenceModel/
โ”‚   โ”œโ”€โ”€ NHibernate/
โ”‚   โ”œโ”€โ”€ MongoDb/
โ”‚   โ””โ”€โ”€ Migrations/
โ”œโ”€โ”€ Messaging/
โ”‚   โ”œโ”€โ”€ MyService.MessagingModel/
โ”‚   โ””โ”€โ”€ MyService.FlowModel.[MassTransit|NServiceBus]/
โ”œโ”€โ”€ ActorModel/
โ”‚   โ””โ”€โ”€ MyService.ActorModel.[Orleans|Dapr|Akka]/
โ”œโ”€โ”€ Scheduler/
โ”‚   โ””โ”€โ”€ MyService.SchedulerModel.[Hangfire|Quartz]/
โ”œโ”€โ”€ ServiceModel/
โ”‚   โ””โ”€โ”€ MyService.ServiceModel.[RestApi|Grpc|GraphQL|SignalR|Function]/
โ”œโ”€โ”€ AI/
โ”‚   โ””โ”€โ”€ MyService.SemanticKernel/
โ”œโ”€โ”€ Bot/
โ”‚   โ””โ”€โ”€ MyService.BotModel/
โ”œโ”€โ”€ Application/
โ”‚   โ”œโ”€โ”€ MyService.ApplicationModel/
โ”‚   โ””โ”€โ”€ MyService.Application/
โ”œโ”€โ”€ Infrastructure/
โ”‚   โ”œโ”€โ”€ MyService.DockerCompose/
โ”‚   โ””โ”€โ”€ MyService.InfrastructureModel/
โ”œโ”€โ”€ Testing/
โ”‚   โ”œโ”€โ”€ UnitTests/
โ”‚   โ”œโ”€โ”€ AcceptanceTests/
โ”‚   โ””โ”€โ”€ ArchitectureTests/
โ”œโ”€โ”€ Architecture/
โ”‚   โ”œโ”€โ”€ ArchitectureModel/
โ”‚   โ””โ”€โ”€ DiagramAsCodeModel/

๐Ÿ“ฆ Each folder above is a separate project, promoting modularity and enabling precise dependency management.


๐Ÿงฑ Core Layers

๐Ÿ”น Common Layer

Project Purpose
MyService Base constants, errors, service-wide helpers
MyService.Options Strongly-typed config and options pattern
MyService.Metrics Prometheus/OpenTelemetry metrics definitions

๐Ÿ”น Domain Layer

Project Purpose
EntityModel Aggregates, value objects, enums
DomainModel Interfaces for use cases, services, events
DomainModel.Impl FluentValidation, orchestrators, processors

๐Ÿ”น Persistence Layer

Project Purpose
PersistenceModel Repository and specification interfaces
PersistenceModel.NHibernate NHibernate mappings and implementations
PersistenceModel.MongoDb Mongo-specific repository implementations
DatabaseModel.Migrations FluentMigrator-based SQL migration scripts
MongoDb.Migrations Optional: Mongo migration strategies

๐Ÿ”Œ Integrations & Interfaces

๐Ÿ”น Messaging

Project Purpose
MessagingModel Command, event, query contracts
FlowModel.MassTransit Consumers, sagas, outbox logic
FlowModel.NServiceBus NSB-specific messaging logic

๐Ÿ”น Actor Model

Project Purpose
ActorModel.Orleans Grain interfaces, implementations, timers
ActorModel.Dapr Actor registration, handlers, metadata
ActorModel.Akka Akka actor tree (if enabled)

๐Ÿ”น ServiceModel (API)

Project Purpose
RestApi REST controllers, Swagger, filters
Grpc Proto files, services, interceptors
GraphQL Schema, queries, mutations
SignalR Hub definition and real-time endpoints
AzureFunction Functions triggered by HTTP, queue, cron

๐Ÿ”น Scheduler

Project Purpose
SchedulerModel.Hangfire Job registration, dashboards, retries
SchedulerModel.Quartz Quartz.NET job logic (optional)

๐Ÿ”น AI and Bot

Project Purpose
SemanticKernel Skills, planners, connectors, plugins
BotModel Microsoft Bot Framework integration (dialogs, cards, state)

๐Ÿงฉ Application Layer

Project Purpose
ApplicationModel DI container registration, middleware, telemetry setup
Application Microservice host entry point (Main method)

๐Ÿ—๏ธ Infrastructure

Project Purpose
DockerCompose Local multi-container orchestration
InfrastructureModel Pulumi-based IaC for Azure (Key Vault, App Service, Service Bus, etc.)

โœ… Testing Layer

Project Type
UnitTests Pure logic/unit test coverage
AcceptanceTests SpecFlow + BDD integration tests
ArchitectureTests Dependency flow, structure, DDD validation

๐Ÿงญ Architecture & Documentation

Project Purpose
ArchitectureModel Mermaid/C4 diagrams, project maps
DiagramAsCodeModel Python-based diagram generation (e.g., Diagrams.net or Graphviz)

๐Ÿงช Traceability and Design Discipline

  • ๐Ÿ”Ž Each concern has its own bounded project
  • ๐Ÿšซ Circular references are disallowed by structure
  • ๐Ÿง  Agents and humans both understand and extend generated solutions
  • โœ… Fully CI/CD-friendly, each project can be:

    • Independently tested
    • Versioned in NuGet feeds
    • Deployed as containers

โœ… Summary

  • The ConnectSoft microservice solution is structured for clarity, modularity, and scalability
  • Each project aligns to a DDD or Clean Architecture principle
  • All cross-cutting concerns and host features are optionally included based on template parameters
  • AI agents can reason about, extend, and deploy generated code with traceable precision

๐Ÿง  Domain Layer and DDD Foundation

The Domain Layer represents the core business logic of the microservice, modeled following Domain-Driven Design (DDD) principles. It is independent of infrastructure, databases, protocols, and frameworks โ€” making it the most stable and testable part of the system.


๐Ÿงฑ DDD Tactical Patterns Supported

The template includes full support for the following tactical building blocks:

Concept Description
Entity Object with identity over time (e.g., Order, Invoice)
Aggregate Root A consistency boundary containing entities and rules
Value Object Immutable object identified by its value (e.g., Money, DateRange)
Enumeration Domain-specific enum alternative (with behavior and metadata)
Domain Service Stateless logic that doesn't naturally fit within an entity
Domain Event Significant business occurrence to be published internally/externally
Specification Encapsulated, composable business rule/query logic

๐Ÿ“ฆ Projects Involved

Project Description
EntityModel Contains entities, aggregates, value objects, enumerations
DomainModel Defines use cases, domain services, and events as interfaces
DomainModel.Impl Implements domain services and validation using FluentValidation

All of these are generated when a persistence model (NHibernate or MongoDb) is selected.


๐Ÿ“‚ Folder Structure Example

EntityModel/
  โ”œโ”€โ”€ Entities/
  โ”‚   โ””โ”€โ”€ Order.cs
  โ”œโ”€โ”€ ValueObjects/
  โ”‚   โ””โ”€โ”€ Money.cs
  โ”œโ”€โ”€ Enumerations/
  โ”‚   โ””โ”€โ”€ OrderStatus.cs

DomainModel/
  โ”œโ”€โ”€ Events/
  โ”‚   โ””โ”€โ”€ OrderPlacedEvent.cs
  โ”œโ”€โ”€ Services/
  โ”‚   โ””โ”€โ”€ IOrderPricingService.cs
  โ”œโ”€โ”€ UseCases/
  โ”‚   โ””โ”€โ”€ IPlaceOrderHandler.cs

DomainModel.Impl/
  โ”œโ”€โ”€ Services/
  โ”‚   โ””โ”€โ”€ DefaultOrderPricingService.cs
  โ”œโ”€โ”€ Validators/
  โ”‚   โ””โ”€โ”€ PlaceOrderValidator.cs

๐Ÿ“Œ Aggregate Example

public class Order : AggregateRoot<Guid>
{
    private readonly List<OrderItem> _items = new();

    public CustomerId CustomerId { get; private set; }
    public OrderStatus Status { get; private set; }

    public void Place()
    {
        if (_items.Count == 0)
            throw new InvalidOperationException("Order must have at least one item.");

        Status = OrderStatus.Placed;
        AddDomainEvent(new OrderPlacedEvent(Id));
    }
}

โœ… Built-in support for raising domain events from within aggregates.


๐Ÿ“š FluentValidation Integration

Every command/use case has a matching validator:

public class PlaceOrderValidator : AbstractValidator<PlaceOrderInput>
{
    public PlaceOrderValidator()
    {
        RuleFor(x => x.CustomerId).NotEmpty();
        RuleFor(x => x.Items).NotEmpty().WithMessage("Order must contain items.");
    }
}

Validators are automatically wired via the ApplicationModel and executed before use cases are invoked.


๐Ÿ“ค Domain Events

  • Domain events implement IDomainEvent
  • Can be enriched with metadata (correlationId, source aggregate, etc.)
  • Published to:

    • Local in-process handlers
    • Outbox (via MassTransit or NServiceBus)
    • External pub/sub systems
public record OrderPlacedEvent(OrderId OrderId) : IDomainEvent;

๐Ÿง  Use Case Model

Each use case follows a request/response pattern and is implemented as a processor/retriever interface pair:

public interface IPlaceOrderHandler : IUseCase<PlaceOrderInput, PlaceOrderOutput> { }

This pattern:

  • Enforces a clean application boundary
  • Allows injection of cross-cutting behaviors (e.g., caching, telemetry, validation)
  • Maps to service interfaces (REST, gRPC, GraphQL)

๐Ÿ”„ Specification Pattern

The template includes optional specification support for NHibernate/MongoDB:

public class OrdersByCustomerSpec : Specification<Order>
{
    public OrdersByCustomerSpec(CustomerId customerId)
    {
        Criteria = x => x.CustomerId == customerId;
    }
}

โœ… Composable, testable query logic โœ… Automatically translated to LINQ or Mongo drivers


๐Ÿงช Testing Focus

  • Domain layer is fully testable without infrastructure
  • Includes:

    • Aggregate behavior tests
    • Validator tests
    • Use case logic with mocks
    • Domain event dispatching

โœ… Summary

  • The Domain Layer reflects business logic only
  • Fully decoupled from transport, database, and hosting
  • Follows rich DDD tactical modeling
  • Easy to test, extend, and validate
  • Emits events, enforces invariants, and defines use case contracts

๐Ÿ—ƒ๏ธ Persistence Layer and Data Models

The Persistence Layer abstracts the interaction between the domain model and the underlying data storage technology. It supports both relational and non-relational databases with built-in repository patterns, specification support, and optional migration infrastructure.

  • โœ… Cleanly separated from business logic
  • โœ… Swap-in support for NHibernate, MongoDB, or none
  • โœ… Optional support for second-level cache (e.g., Redis)

๐Ÿงฑ Core Projects

Project Purpose
PersistenceModel Repository contracts, specifications, queries
PersistenceModel.NHibernate NHibernate-based ORM implementation
PersistenceModel.MongoDb MongoDB provider (Mongo Driver + fluent mapping)
DatabaseModel.Migrations SQL schema migrations using FluentMigrator
MongoDb.Migrations Optional Mongo migration definitions (via MongoDBMigrations)

Generated based on CLI flags: --PersistenceModelType, --UseMigrations, --NHibernateDialectType


โš™๏ธ Configuration Parameters

Parameter Type Purpose
--PersistenceModelType NHibernate, MongoDb, None
--NHibernateDialectType SqlServer, PostgreSQL, MySQL
--NHibernateSecondLevelCacheType Redis, None
--DatabaseName string Used in connection string generation
--UseMigrations bool Enables FluentMigrator or MongoDb migrations

๐Ÿงฉ Repository and Specification Pattern

public interface IOrderRepository : IRepository<IOrder, Guid>
{
    Task<IOrder?> GetByCustomerIdAsync(CustomerId customerId, CancellationToken ct);
}
public class OrdersByCustomerSpec : Specification<IOrder, Guid>
{
    public OrdersByCustomerSpec(CustomerId customerId)
    {
        Criteria = o => o.CustomerId == customerId;
    }
}
  • โœ… Automatically wired into NHibernate or MongoDb LINQ
  • โœ… Keeps business logic clean
  • โœ… Supports unit testing without actual storage

๐Ÿ—‚๏ธ NHibernate ORM Support

If --PersistenceModelType NHibernate is selected:

  • Fluent mappings auto-generated for aggregates and value objects
  • Configured using:
<hibernate-configuration>
  <session-factory>
    <property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
    ...
  </session-factory>
</hibernate-configuration>
  • Optional Redis caching:
"NHibernate": {
  "SecondLevelCache": "Redis",
  "Redis": {
    "ConnectionString": "localhost:6379"
  }
}

๐Ÿƒ MongoDB Support

If --PersistenceModelType MongoDb:

  • Uses native Mongo driver with fluent class mapping
  • Supports:

    • Attribute-based index creation
    • Mapping profiles per aggregate
    • GridFS (optional)

๐Ÿ—ƒ๏ธ Migrations Support

If --UseMigrations true:

Tech Tool
SQL DBs FluentMigrator (table/index scripts)
MongoDB MongoDBMigrations (collection creation, seeders)

๐Ÿ”„ Migrations run automatically on app startup (optional environment guards)


๐Ÿงช Testing Utilities

  • In-memory NHibernate database with SQLite for local/unit tests
  • Mongo memory test cluster (optional)
  • Database mocking abstractions available via interface injection

๐Ÿง  AI Usage

  • Agents receive mappings from EntityModel to generate NHibernate/Mongo mappings
  • Event sourcing support is future-compatible (TBD via feature flag)
  • Generated specifications and repository interfaces help agents understand query models

โœ… Summary

  • Supports relational and NoSQL persistence via NHibernate and MongoDB
  • Aligned with repository and specification patterns
  • Optional support for migrations, second-level cache, and audit
  • Cleanly isolated from domain logic โ€” pluggable and testable
  • Used by both developers and generation agents to extend or scaffold features

๐Ÿ“ก Messaging Layer and Event-Driven Patterns

The Messaging Layer enables microservices to communicate asynchronously through events, commands, and queries, supporting:

  • โœ… Event-Driven Architecture (EDA)
  • โœ… Domain Event Publishing
  • โœ… Sagas and Process Managers
  • โœ… Integration with external systems
  • โœ… Outbox pattern and retries

The messaging model is pluggable, allowing use of MassTransit or NServiceBus, or disabling messaging entirely.


๐Ÿ“ฆ Core Projects

Project Purpose
MessagingModel Contracts (commands, events, queries)
FlowModel.MassTransit Consumers, publishers, outbox, saga logic
FlowModel.NServiceBus Endpoint configuration, handlers, saga logic

โš™๏ธ Template Parameters

Parameter Description
--MessagingModelType MassTransit, NServiceBus, None
--MassTransitTransport SqlServer, RabbitMQ, AzureServiceBus
--MassTransitPersistence NHibernate, MongoDB, CosmosDB, Dapper
--NServiceBusTransport SqlServer, RabbitMQ
--NServiceBusPersistence SQL, MongoDB, CosmosDB
--UseOutboxPattern Implicit for both bus options
--NServiceBusEndpointName Used to configure endpoint routing

๐Ÿงฉ Messaging Model Structure

๐Ÿ“‚ MessagingModel/

Commands/
  โ””โ”€โ”€ CreateOrderCommand.cs
Events/
  โ””โ”€โ”€ OrderPlacedEvent.cs
Queries/
  โ””โ”€โ”€ GetOrderDetailsQuery.cs

All contracts implement marker interfaces:

  • ICommand<TResponse>
  • IEvent
  • IQuery<TResponse>

๐Ÿ” MassTransit Flow Model

โœ… Features:

  • Built-in support for:
    • Consumers and message pipelines
    • Saga state machines
    • Retry policies
    • Outbox pattern
  • Transport abstraction for:
    • RabbitMQ
    • Azure Service Bus
    • SQL Server
  • Persistence:
    • NHibernate, MongoDB, CosmosDB
public class OrderCreatedConsumer : IConsumer<OrderCreatedEvent>
{
    public async Task Consume(ConsumeContext<OrderCreatedEvent> context)
    {
        // handle event
    }
}

๐Ÿงฐ Configuration via MassTransitOptions


๐Ÿ“ฆ NServiceBus Flow Model

โœ… Features:

  • Endpoint orchestration with:
    • Command handlers
    • Event handlers
    • Saga orchestration
  • Full compatibility with:
    • SQL, CosmosDB, MongoDB persistence
    • SQL Server or RabbitMQ transports
  • Health checks and heartbeat support
  • Built-in retries, dead-letter queues, metrics
public class OrderCreatedHandler : IHandleMessages<OrderCreatedEvent>
{
    public Task Handle(OrderCreatedEvent message, IMessageHandlerContext context)
    {
        // business logic
        return Task.CompletedTask;
    }
}

Configuration via NServiceBusOptions + License.xml is automated.


๐Ÿง  Domain Event Integration

All domain events raised from aggregates (in EntityModel) are:

  1. Captured via IDomainEvent
  2. Dispatched to messaging layer via internal IEventPublisher
  3. Published through bus to external systems

โœ… Enables internal decoupling + external integration


๐Ÿ” Saga Orchestration

Long-running workflows can be modeled using:

Feature MassTransit NServiceBus
State Machines โœ… โœ…
Correlation โœ… โœ…
Timeout messages โœ… โœ…
Storage NHibernate, MongoDb, Cosmos SQL, MongoDb, Cosmos

Optional saga examples included:

  • OrderCheckoutSaga
  • PaymentProcessingSaga

๐Ÿงช Testing Support

  • In-memory transport for unit/integration tests
  • WireMock or message spies supported
  • Use Harness in MassTransit or TestingContext in NSB

๐Ÿง  AI Agent Compatibility

Messaging model is generated dynamically by:

  • Extracting contract info from DomainModel.yaml
  • Mapping events to handlers or external subscribers
  • Injecting message schema metadata for AI-aware routing

โœ… Summary

  • Supports both MassTransit and NServiceBus
  • Enables full EDA and saga orchestration
  • All messages follow contract-first design
  • Domain events are auto-published
  • Configurable transports and persistence per service
  • Includes outbox, DLQ, and retry mechanisms

๐ŸŒ Service Model and API Interfaces

The ServiceModel layer exposes the microservice's public API using various protocols and interfaces. Each model is generated based on the selected --ServiceModelType and follows Clean Architecture by mapping external requests to internal use cases.


๐Ÿ“ฆ Supported API Models

API Type Project Description
REST API ServiceModel.RestApi Controller-based routing using ASP.NET Core
gRPC ServiceModel.Grpc Proto-defined services with support for interceptors
GraphQL ServiceModel.GraphQL HotChocolate-powered schema-first APIs
SignalR ServiceModel.SignalR Real-time bi-directional streaming
Azure Functions ServiceModel.AzureFunction Event-driven, serverless handlers
CoreWCF ServiceModel.CoreWCF WCF compatibility layer (optional)
Service Fabric ServiceModel.ServiceFabric Stateful service model (optional)

โš™๏ธ Template Parameters

Parameter Options
--ServiceModelType RestApi, Grpc, GraphQL, SignalR, AzureFunction, None
--Swagger Enables Swagger/OpenAPI for REST
--CORS Enables Cross-Origin Resource Sharing
--HttpPort / --HttpsPort Custom port binding in launchSettings.json

๐Ÿ” Clean Entry Point Mapping

All service models map to use case handlers defined in DomainModel:

public interface IPlaceOrderHandler : IUseCaseHandler<PlaceOrderInput, OrderDto> { }

These handlers are called from controllers, gRPC services, or function triggers depending on interface.


๐ŸŒ REST API

๐Ÿ“‚ Structure

ServiceModel.RestApi/
  โ”œโ”€โ”€ Controllers/
  โ”‚   โ””โ”€โ”€ OrdersController.cs
  โ”œโ”€โ”€ Filters/
  โ”œโ”€โ”€ Swagger/
  • Uses minimal or standard controllers ([ApiController])
  • Integrated with:
    • ProblemDetails middleware
    • FluentValidation (in domain services)
    • AutoMapper (via profile scanning)

โœ… Swagger UI at /swagger โœ… API versioning supported


โšก gRPC API

๐Ÿ“‚ Structure

ServiceModel.Grpc/
  โ”œโ”€โ”€ Protos/
  โ”‚   โ””โ”€โ”€ order_service.proto
  โ”œโ”€โ”€ Services/
  โ”‚   โ””โ”€โ”€ OrderService.cs
  • Implements Grpc.Core.Server registration
  • Adds:
    • Logging interceptor
    • Validation interceptor
    • Rich error details (RFC standard support)

โœ… Used for low-latency messaging between services โœ… Supports unary, streaming, and bidirectional RPC


๐Ÿ”Ž GraphQL API

๐Ÿ“‚ Structure

ServiceModel.GraphQL/
  โ”œโ”€โ”€ Schema/
  โ”‚   โ””โ”€โ”€ OrderType.cs
  โ”œโ”€โ”€ Queries/
  โ”œโ”€โ”€ Mutations/
  • Powered by HotChocolate
  • Schema-first or code-first support
  • Complex filtering, paging, federation-ready

โœ… Easily maps to domain queries โœ… Exposes introspection endpoints


๐Ÿ“ก SignalR (Real-Time)

๐Ÿ“‚ Structure

ServiceModel.SignalR/
  โ”œโ”€โ”€ Hubs/
  โ”‚   โ””โ”€โ”€ OrderHub.cs
  • Implements typed hubs
  • Integrated with:
    • Auth (JWT)
    • Multi-tenant channeling
    • Live updates via internal events

โœ… Used for dashboards, UI notifications, or agent callbacks


โ˜๏ธ Azure Function Host

๐Ÿ“‚ Structure

ServiceModel.AzureFunction/
  โ”œโ”€โ”€ HttpTriggers/
  โ”œโ”€โ”€ QueueTriggers/
  โ”œโ”€โ”€ TimerTriggers/
  • Serverless compute model
  • Maps use cases to:
    • REST-like endpoints
    • Timer-based schedulers
    • Queue/bus subscribers

โœ… Enables cost-efficient, scalable, event-driven APIs


๐Ÿ›ก๏ธ Cross-Cutting Features

Feature Description
CORS Auto-configured via CorsExtensions
Authentication JWT bearer validation with role/policy guards
ProblemDetails RFC 7807-compliant error responses
Swagger UI REST-only โ€“ interactive docs
Validation FluentValidation auto-wiring for request models

๐Ÿงช Testing Support

  • REST: Testable via HTTP clients (e.g., WebApplicationFactory)
  • gRPC: GrpcChannel and in-memory server options
  • GraphQL: Unit test resolvers
  • Azure Functions: Durable functions integration test kits

๐Ÿง  Agent Integration

  • AI agents extract all use case entrypoints and infer:
    • Required inputs
    • Contracts and DTOs
    • Invocation routes for bots or orchestrators

โœ… Supports skill scaffolding for Semantic Kernel agents โœ… Compatible with BotFramework conversation handlers


โœ… Summary

  • Supports multiple service interface models
  • Each API layer maps cleanly to domain use cases
  • Auto-wired middleware for security, validation, telemetry
  • REST, gRPC, GraphQL, SignalR, Functions all align to the same domain

๐Ÿง  Actor Model Integration and Virtual Actors

The ActorModel layer supports stateful, distributed, and concurrent logic using virtual actor patterns. Actors encapsulate behavior + state and can operate independently, making them ideal for:

  • Real-time collaborative applications
  • Distributed task orchestration
  • AI skill execution
  • Stateful workflows and domain boundaries

๐Ÿ” Supported Actor Models

Framework Project Description
Orleans ActorModel.Orleans Microsoft virtual actor framework for .NET
Dapr ActorModel.Dapr Sidecar-based actor runtime with state API
Akka.NET ActorModel.Akka Classic message-based actors (optional)

๐Ÿ“Œ Only one model is included based on the --ActorModelType parameter:

  • Orleans, Dapr, Akka, or None

โš™๏ธ Template Parameters

Parameter Description
--ActorModelType Selects the actor model: Orleans, Dapr, Akka, None
--UseOpenAI Enables actor-based AI skill execution
--UseSemanticKernel Allows actor-triggered semantic orchestration

๐Ÿงฑ Orleans Actor Model

๐Ÿ“‚ Structure

ActorModel.Orleans/
  โ”œโ”€โ”€ Grains/
  โ”‚   โ””โ”€โ”€ IOrderGrain.cs
  โ”‚   โ””โ”€โ”€ OrderGrain.cs
  โ”œโ”€โ”€ Timers/
  โ””โ”€โ”€ Extensions/
Feature Description
Virtual actor lifecycle No explicit activation or deactivation
Timers/reminders Built-in retry and scheduling support
Built-in clustering Azure, Redis, ADO.NET, local
Telemetry hooks OpenTelemetry spans, tags, grains

โœ… Auto-registered via OrleansExtensions.cs โœ… Full support for stream-based messaging


๐ŸŒŠ Dapr Actor Model

๐Ÿ“‚ Structure

ActorModel.Dapr/
  โ”œโ”€โ”€ Actors/
  โ”‚   โ””โ”€โ”€ OrderActor.cs
  โ”œโ”€โ”€ Interfaces/
  โ”‚   โ””โ”€โ”€ IOrderActor.cs
Feature Description
Cross-language actors API-based actor runtime
State management Key-value with state stores (Redis, Cosmos, etc.)
Hosted with sidecar Dapr sidecar handles registration
Pub/Sub + secrets Easily combined with Dapr messaging patterns

โœ… Registered via Dapr component manifest โœ… Actor timers, state APIs exposed via HTTP/gRPC


๐ŸŽญ Akka.NET Actor Model (Optional)

Feature Description
Classic actor model Mailbox, supervision, hierarchies
More complex patterns Sharding, persistence, FSM
Less integrated with .NET ecosystem Used only for specialized cases

๐Ÿ”Œ Common Features for All Actor Models

  • โœ… AI orchestration (each actor can invoke Semantic Kernel skills)
  • โœ… Message dispatch via event bus or direct HTTP
  • โœ… Actor health probes and logging integration
  • โœ… Multi-tenant context propagation (e.g., TenantId, CorrelationId)

๐Ÿง  Sample Grain Contract (Orleans)

public interface IBankAccountGrain : IGrainWithStringKey
{
    Task Deposit(decimal amount);
    Task Withdraw(decimal amount);
    Task<decimal> GetBalance();
}

๐Ÿ—‚๏ธ Use Cases Examples Enabled

  • BankAccountGrain with deposit/withdraw
  • AI TaskGrain for Semantic Kernel orchestration
  • DocumentWorkflowGrain for long-running approval
  • ChatSessionGrain for real-time Bot integration

๐Ÿงช Testing

  • Orleans test cluster (in-memory)
  • Dapr test host and mocked sidecar
  • Actor messaging tested with BDD + ScenarioContext

๐Ÿง  Agent Integration

  • Agents use ActorModel.yaml or DomainModel.yaml to:

    • Generate new grains/actors
    • Inject actor logic into workflows
    • Map actor interfaces to APIs or ports

โœ… Compatible with planner-based orchestration โœ… Stateful example actor support for AI assistants, semantic memory, long-lived processes


โœ… Summary

  • Provides virtual actor patterns for distributed, isolated, persistent logic
  • Supports Orleans, Dapr, or Akka, selected at generation time
  • Fully integrates with OpenTelemetry, semantic AI, and event-driven systems
  • Can power workflow engines, chat states, job controllers, and more

โฑ๏ธ Scheduler and Background Job Models

The SchedulerModel provides support for background processing and scheduled jobs, enabling microservices to execute logic outside of direct request/response flows.

Use cases include:

  • Periodic cleanups or batch tasks
  • Time-based triggers (e.g., reminder notifications)
  • Long-running workflows
  • Asynchronous job queues

๐Ÿงฉ Supported Scheduling Frameworks

Scheduler Project Description
Hangfire SchedulerModel.Hangfire Background jobs with retry, dashboards, CRON
Quartz.NET SchedulerModel.Quartz Enterprise-grade job scheduler
Azure Functions ServiceModel.AzureFunction Timer-based execution in serverless context

The template generates the correct scheduling model depending on --SchedulerModelType or --ServiceModelType.


โš™๏ธ Template Parameters

Parameter Description
--SchedulerModelType Hangfire, Quartz, or None
--ServiceModelType If set to AzureFunction, includes timer triggers
--UseOpenAI / --UseSemanticKernel Jobs can call AI skills
--UseFeatureFlags Jobs can be conditionally registered

๐Ÿ”ง Hangfire Integration

๐Ÿ“‚ Structure

SchedulerModel.Hangfire/
  โ”œโ”€โ”€ Jobs/
  โ”‚   โ””โ”€โ”€ CleanupJob.cs
  โ”œโ”€โ”€ Configuration/
  โ””โ”€โ”€ Extensions/
Feature Description
CRON support Declarative or programmatic
Retry and retry delay Out-of-the-box
Dashboard /hangfire secured endpoint
Storage SQL Server, Redis, or in-memory options
Distributed lock support Built-in for cluster-safe execution

โœ… Registered via UseHangfire() and AddHangfireJobs()


๐Ÿ”ง Quartz.NET Integration

๐Ÿ“‚ Structure

SchedulerModel.Quartz/
  โ”œโ”€โ”€ Jobs/
  โ”‚   โ””โ”€โ”€ GenerateInvoicesJob.cs
  โ””โ”€โ”€ QuartzConfiguration/
Feature Description
CRON or Interval triggers Declarative or fluent API
Durable job definitions Persistence in DB (optional)
Clustering support Quartz.NET built-in
Middleware hooks Add retry, tracing, correlation ID

โœ… Jobs registered at startup via QuartzExtensions.RegisterJobs() โœ… Hosted as part of the main worker process or external worker


๐ŸŒฉ๏ธ Azure Function Timer Triggers

๐Ÿ“‚ Structure

ServiceModel.AzureFunction/
  โ””โ”€โ”€ TimerTriggers/
      โ””โ”€โ”€ SendDigestEmailsFunction.cs
Feature Description
CRON expressions "0 */30 * * * *" format
Native Azure scaling Based on trigger volume
AppSettings based Bindings from host.json and environment
Durable Tasks Optional extension for workflows

โœ… Works in both isolated and full-function runtime


๐Ÿงช Example: Registering a Hangfire Job

public class SendEmailRemindersJob : IBackgroundJob
{
    public async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        // logic to send reminders
    }
}
RecurringJob.AddOrUpdate<SendEmailRemindersJob>(
    job => job.ExecuteAsync(CancellationToken.None),
    Cron.Hourly);

๐Ÿงช Testing Background Jobs

Scenario Tooling
Job logic unit test xUnit or MSTest
Schedule/CRON test CronUtils or test clock
Hangfire dashboard test Selenium or headless browser
Mock time for timers TestServer + DateTimeProvider override

๐Ÿง  AI Integration with Jobs

  • Jobs can invoke Semantic Kernel skills or trigger AI workflows
  • Example: DailySummaryJob โ†’ calls SummarizeDomainActivitySkill
  • AI-based planners can register jobs dynamically (future roadmap)

โœ… Ideal for automating reports, insights, event summaries, feedback loops


๐Ÿ”’ Security & Observability

  • Hangfire and Quartz jobs:

    • Use ILogger<> for tracing
    • Include correlation ID + tenant context
    • Optional OpenTelemetry spans
  • Hangfire dashboard:

    • Protected via JWT / policy-based guards

โœ… Summary

  • Supports robust background job execution with:

    • Retry logic
    • Metrics
    • CRON scheduling
    • AI integration
    • Enables serverless, clustered, or hosted models
    • Cleanly integrated into the Clean Architecture flow

๐Ÿค– Semantic Kernel and AI Extensions

The SemanticKernel integration layer empowers microservices with AI orchestration capabilities, enabling them to:

  • Invoke LLM-backed skills and workflows
  • Respond to natural language prompts
  • Execute AI-enhanced tasks in background jobs, APIs, or actors
  • Collaborate with other services using planner-generated flows

๐Ÿง  This is the foundation for ConnectSoft AI Agents, intelligent assistants, and autonomous feature delivery.


๐Ÿงฉ Core Project

AI/
โ””โ”€โ”€ SemanticKernel/
    โ”œโ”€โ”€ Skills/
    โ”œโ”€โ”€ Plugins/
    โ”œโ”€โ”€ Configuration/
    โ””โ”€โ”€ KernelHost.cs

โœ… Generated when --UseSemanticKernel true or an agent explicitly activates this feature.


โš™๏ธ Template Parameters

Parameter Description
--UseSemanticKernel Enables SK kernel host, plugin infrastructure
--UseOpenAI Adds connectors for OpenAI, Azure OpenAI
--UseMicrosoftBotBuilder Enables conversation flow using SK-based responses
--ActorModelType Can link SK flows to actors
--ServiceModelType Allows SK triggers from APIs or gRPC

๐Ÿง  Skills and Plugins Structure

Folder Purpose
Skills/ C#-based native skills for AI workflows
Plugins/ Prompt-template based skills (functions)
KernelHost.cs Central entry point to configure kernel, memory, and planners

Example: Native Skill

public class CreateInvoiceSkill
{
    [KernelFunction]
    public Task<string> GenerateInvoiceAsync(string customerId)
    {
        // domain call here
        return Task.FromResult("Invoice created for " + customerId);
    }
}

Example: Prompt Plugin

Plugins/CustomerSupport/
โ””โ”€โ”€ SummarizeTicket/
    โ”œโ”€โ”€ config.json
    โ””โ”€โ”€ skprompt.txt

๐Ÿ”Œ LLM Connectors

Out-of-the-box support for:

  • โœ… OpenAI (ChatGPT, GPT-4)
  • โœ… Azure OpenAI
  • โœ… Ollama (local models)
  • โœ… HuggingFace
  • โœ… PromptFlow (plugin-based)
  • โœ… RAG: Retrieval-Augmented Generation (via memory store)

๐Ÿง  Kernel Features Enabled

Capability Description
Planner Support Sequential, Stepwise, or Function-based plans
Memory Support In-memory or external stores (e.g., Redis, CosmosDB)
Context Propagation Correlation ID, tenant ID, execution ID
Streaming Responses For chat, SignalR, or BotFramework
Logging and Observability Via OpenTelemetry spans, semantic traces

๐Ÿ“ก Integration Points

Runtime How SK is Used
REST API Expose AI prompt endpoints or chat endpoints
gRPC / GraphQL Create AI-enhanced services
Background Job Automate scheduled AI summaries, insights, decisions
Actor Attach skills to a single grain or actor type
Bot Framework Use skills as part of adaptive dialog responses
Message Consumers Trigger AI from events and route output via command bus

๐Ÿงช Testing & Tooling

Tool Use
KernelTestHost Mock LLMs in unit tests
Prompt Engineering Use config.json and promptflow.json for structure
AIOutputRecorder Capture output of skills in event log / observability layer

โœ… Semantic test harness included โœ… Optional skill metrics (sk_invocations_total, etc.)


๐Ÿ“– Example Use Cases

  • GenerateCustomerSummarySkill โ†’ called via gRPC or background job
  • ValidateInsuranceClaimSkill โ†’ runs inside a grain
  • RouteSupportTicketSkill โ†’ triggered via SignalR
  • OnboardingPlanner โ†’ multi-step process planner
  • TranslateLanguageSkill โ†’ exposed via API and Bot

๐Ÿง  Agent-Aware Structure

  • All skills are discoverable by agents via directory structure and metadata
  • AI agents can:

    • Register new skills
    • Rewire flows dynamically
    • Auto-generate plugin prompts from domain events

โœ… Fully composable into end-to-end autonomous execution chains


โœ… Summary

  • The template includes first-class AI orchestration support
  • Built on Semantic Kernel, with connectors, skills, memory, and plugins
  • Ready for use in APIs, bots, actors, events, and planners
  • Enables agentic orchestration across microservices and AI workflows

๐Ÿ’ฌ Microsoft Bot Framework Integration

The BotModel layer enables microservices to act as conversational agents, integrating with the Microsoft Bot Framework to deliver:

  • Interactive chat experiences
  • Adaptive dialogs
  • OAuth-based identity flows
  • AI-enhanced skills and prompts
  • Voice or omnichannel connectivity (Teams, Telegram, Web)

This allows microservices to expose business logic conversationally, powered by both domain use cases and Semantic Kernel skills.


๐Ÿ“ฆ Core Project

Bot/
โ””โ”€โ”€ BotModel/
    โ”œโ”€โ”€ Dialogs/
    โ”œโ”€โ”€ Cards/
    โ”œโ”€โ”€ Controllers/
    โ”œโ”€โ”€ Configuration/
    โ””โ”€โ”€ Middleware/

โœ… This is generated if --UseMicrosoftBotBuilder true.


โš™๏ธ Template Parameters

Parameter Description
--UseMicrosoftBotBuilder Enables bot model scaffolding
--UseSemanticKernel Connects bot dialogs to SK skills
--UseOpenAI Enables natural language fallback or enrichment
--ServiceModelType RestApi must be included to expose /api/messages
--UseAuthentication Configures OAuth2 flows with Bot Framework
--ActorModelType Optional: link Bot sessions to actor state

๐Ÿ”Œ Key Features Included

Feature Description
Adaptive Dialogs Supports conditional and multi-step dialogs
OAuth Support Integrated with Azure AD or custom identity provider
Conversation State Memory and transcript support
Channel Support Web Chat, MS Teams, Telegram, Facebook, WhatsApp
Error Handling Global exception handler and fallback replies
Adaptive Cards Custom card rendering with rich data from the domain layer
AI Orchestration Integration with SK planners or OpenAI completions

๐Ÿ”„ Bot Runtime Flow

sequenceDiagram
    User->>BotController: POST /api/messages
    BotController->>Adapter: Process activity
    Adapter->>Dialog: Start or continue dialog
    Dialog->>UseCaseHandler: Call domain logic
    Dialog->>SemanticKernel: Call SK skill (optional)
    Dialog->>User: Send adaptive card or text response
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿง  Adaptive Dialog Example

public class OnboardingDialog : ComponentDialog
{
    public OnboardingDialog(...) : base(nameof(OnboardingDialog))
    {
        var steps = new WaterfallStep[]
        {
            AskNameAsync,
            ConfirmAsync,
            CompleteAsync
        };

        AddDialog(new WaterfallDialog(nameof(WaterfallDialog), steps));
    }
}

โœ… Each dialog step may call:

  • Domain use case
  • Actor method
  • AI skill
  • Background job
  • Message dispatch

๐Ÿ“ Adaptive Card Support

{
  "type": "AdaptiveCard",
  "version": "1.5",
  "body": [
    { "type": "TextBlock", "text": "Welcome!" }
  ],
  "actions": [
    { "type": "Action.Submit", "title": "Continue", "data": { "action": "next" } }
  ]
}
  • Cards live under BotModel/Cards/
  • Connected to dialog state and tenant context
  • Themeable and data-driven

๐Ÿ” OAuth and Sign-In

  • Supports:

    • Azure AD
    • External identity (e.g., WordPress, Firebase)
    • Uses OAuthPrompt + SignInCard flow
    • Captures token in user state and passes it into service layer

โœ… Required for premium access, personalization, or external APIs


๐Ÿง  Integration with AI & Skills

  • Each bot dialog can invoke Semantic Kernel skills directly
  • Conversations may use:

    • LLM completions (ChatGPT, Azure OpenAI)
    • Summarization, planning, transformation
    • RAG: memory + semantic context

โœ… Response = domain โ†’ AI skill โ†’ card/message


๐Ÿ”„ Connect with Actors

If --ActorModelType is enabled, each conversation can:

  • Be mapped to a grain (e.g., IUserSessionGrain)
  • Maintain state across multiple dialogs
  • Store history, preferences, or progress

๐Ÿงช Testing Support

Test Type Tools
Dialog tests xUnit + Bot Framework test client
Message endpoint Integration test with /api/messages
Card rendering Schema validation and JSON schema testing
OAuth flow Bot Emulator + test IDP

๐Ÿง  Agent Integration

  • Agents can auto-generate dialogs from:

    • Domain use cases
    • Event blueprints
    • AI plugins
  • Dialogs are tagged with metadata to support:

    • Planner orchestration
    • Intent recognition
    • Skill registration

โœ… Enables full conversational integration of business workflows


โœ… Summary

  • Provides a full-featured Bot Framework interface
  • Enables conversational flows over business logic
  • Integrates seamlessly with:

    • OAuth
    • Semantic Kernel
    • Actors
    • Use cases
    • Messaging
    • Delivers enterprise-ready conversational UX for AI and SaaS systems

๐Ÿงฉ Cross-Cutting Concerns and Middleware Pipeline

Cross-cutting concerns (CCCs) are non-functional capabilities that apply across the microservice โ€” regardless of domain logic, transport model, or database engine.

The ConnectSoft Microservice Template includes built-in, opt-in, and composable support for the most important cross-cutting concerns, ensuring:

  • ๐Ÿงฑ Consistency
  • ๐Ÿ” Observability
  • ๐Ÿ” Security
  • ๐Ÿ›  Maintainability
  • ๐Ÿ“Š Extensibility

๐Ÿ”ง Automatically Included Middleware

The template registers all CCCs inside a unified, composable extension chain:

builder.Services.AddMicroserviceServices(configuration);
app.UseMicroservicePipeline();

These extension methods are located in:

Application/
โ””โ”€โ”€ MicroserviceServiceCollectionExtensions.cs
โ””โ”€โ”€ MicroserviceApplicationBuilderExtensions.cs

โœ… Included Cross-Cutting Concerns

Concern Description
Authentication & Authorization JWT bearer, scopes, tenant-based policies
Correlation ID Request ID propagation (via header or trace context)
Tenant Context Header/claim-based multi-tenant resolver
Exception Handling Centralized exception mapping using RFC 7807 (ProblemDetails)
Validation FluentValidation (auto-wired for request models)
Swagger UI Only in development or if --Swagger true
API Versioning Via route segment or header
CORS Configurable origin and methods
Rate Limiting Optional integration (YARP/gateway or custom)
Feature Flags Microsoft.FeatureManagement toggles
Logging Serilog with OpenTelemetry enrichment
Tracing & Metrics OpenTelemetry span/metric auto-registration
Health Checks Liveness/readiness/startup + custom probes

๐Ÿงฑ Middleware Ordering

HTTP Request Pipeline:
  โ†’ CorrelationIdMiddleware
  โ†’ ExceptionHandlingMiddleware
  โ†’ TenantResolutionMiddleware
  โ†’ AuthenticationMiddleware
  โ†’ AuthorizationMiddleware
  โ†’ RequestLoggingMiddleware
  โ†’ EndpointRoutingMiddleware
  โ†’ Swagger/Docs
  โ†’ Health Check Middleware

โœ… You can override this order in Program.cs, or selectively disable middleware in tests.


๐Ÿ” Conditional Activation

Flag Effect
--Swagger Enables Swagger generator and UI
--HealthCheck Enables /health/live, /health/ready, etc.
--FeatureFlags Enables feature toggle system
--OpenTelemetry Injects OTLP metrics, spans, log enrichers
--CORS Enables origin filtering
--Logging Switches between Serilog, Log4Net, or None

๐Ÿงช Exception Handling Example

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
  "title": "Validation Failed",
  "status": 400,
  "traceId": "00-1e0e-...-00",
  "errors": {
    "CustomerId": ["CustomerId is required."]
  }
}

Returned by default via ProblemDetails middleware.


๐Ÿ”’ Tenant Guard Filters

Multi-tenant awareness flows through:

  • HTTP headers (X-Tenant-Id)
  • JWT claims (tenantId)
  • Event headers (MassTransit, NServiceBus)
  • Actor grains and bot dialogs (via context injection)

โœ… TenantContext is available via DI anywhere in the app.


๐Ÿง  Observability Chain

All requests and use cases are automatically:

  • ๐Ÿงญ Enriched with trace ID and tenant ID
  • ๐Ÿ“ก Exposed as OpenTelemetry spans
  • ๐Ÿ“Š Measured with Prometheus-style counters:

  • request_duration_seconds

  • use_case_errors_total
  • message_processed_total

๐Ÿงช Testing CCCs

Concern Test Strategy
Exception handling WebApplicationFactory + assertions
Correlation ID Header injection + response echo
Validation FluentValidation test runner
Swagger JSON schema validator
Health checks /health/ready ping with mock service check
Tenant enforcement Role/claim filters under different user tokens

๐Ÿง  Agent Awareness

  • All CCCs are annotated in metadata for AI orchestration
  • ConnectSoft agents:

    • Inspect Program.cs and MicroservicePipeline
    • Override or extend CCCs via skill hooks (e.g., AddRetryOnUseCaseFailure())

โœ… Summary

The ConnectSoft Microservice Template includes a robust, modular middleware pipeline that supports:

  • โœ… Security, observability, and developer experience
  • โœ… Multi-tenant and multi-environment compatibility
  • โœ… Agentic overrides and runtime flexibility
  • โœ… Automation-ready tracing, logging, and error contracts

๐Ÿ“Š OpenTelemetry, Metrics, and Distributed Tracing

Observability is a first-class concern in the ConnectSoft Microservice Template.

By integrating OpenTelemetry, the template provides structured tracing, logging, and metrics across all execution flows โ€” whether initiated by:

  • REST/gRPC/SignalR APIs
  • Event consumers or message buses
  • Background jobs, actors, bots, or AI skills

๐Ÿ“ˆ All telemetry is zero-config by default, but extensible and pluggable.


โš™๏ธ Template Parameters

Parameter Description
--OpenTelemetry Enables automatic registration of tracing and metrics
--Logging Enables enriched structured logging (Serilog, Log4Net)
--UseApplicationInsights Connects to Azure Monitor AppInsights (optional)
--ResourceMonitoring Adds CPU, memory, thread pool metrics (experimental)

๐Ÿ”ง OpenTelemetry Components Registered

Area Whatโ€™s Wired
Tracing Distributed spans, context propagation (W3C)
Metrics Custom counters, histograms, gauges
Logging Structured logs enriched with trace and tenant context
Exporters OTLP, Prometheus, Jaeger, Zipkin, App Insights
Context CorrelationId, TenantId, TraceId auto-enriched
Semantic Conventions Predefined span names for use cases, events, actors, APIs

๐Ÿ“Œ Tracing: Span Lifecycle

Every request through the microservice results in one or more OpenTelemetry spans, automatically generated and labeled.

Incoming Request โ†’ API Span
                โ†’ UseCase Span
                โ†’ DB Span (e.g., NHibernate)
                โ†’ Messaging Span (if bus used)

Example: REST API call trace

GET /orders/123
โ”œโ”€โ”€ span: HTTP GET /orders/{id}
โ”‚   โ”œโ”€โ”€ span: Execute GetOrderDetailsUseCase
โ”‚   โ””โ”€โ”€ span: NHibernate SQL SELECT ...

โœ… Traces are auto-linked with traceparent headers and persisted by exporters.


๐Ÿงฎ Metrics: Prometheus-Compatible

Default Metrics Included

Metric Description
request_duration_seconds Histogram of request execution time
use_case_execution_total Counter of use case runs
event_processing_duration_seconds Message bus consumer latency
active_grains_count (Orleans/Dapr) current actor load
background_job_success_total Hangfire/Quartz job success count

๐Ÿ“ Exposed at /metrics and scraped by Prometheus.


Custom Metrics with Instrumentation API

private static readonly Histogram<double> OrderValueHistogram =
    MyMeter.CreateHistogram<double>("order_value_distribution");

OrderValueHistogram.Record(order.TotalValue);

โœ… All metrics are enriched with:

  • tenant_id
  • trace_id
  • use_case
  • host_environment

๐Ÿง  Context Enrichment

All telemetry includes:

  • X-Correlation-ID
  • X-Tenant-ID
  • X-Trace-ID (from W3C TraceContext)

โžก Automatically propagated through:

  • HTTP headers
  • gRPC metadata
  • Event headers
  • SignalR context
  • Actor and job execution

๐Ÿ”ญ Exporter Support

Exporter Status
Prometheus โœ… Default
Jaeger โœ… Via environment/launch config
Zipkin โœ… Optional
Azure App Insights โœ… via --UseApplicationInsights
OTLP HTTP / gRPC โœ… Supported for all backend platforms

๐Ÿงช Testing and Validation

Tool Use
OpenTelemetry Collector Forward traces to backends
Prometheus UI Scrape and monitor metrics
Jaeger UI Trace visualization
Serilog TestSink Capture structured logs in tests
ActivitySourceListener Intercept spans in test harness

๐Ÿง  Agent Awareness

  • Spans and metrics are tagged to support:

    • Use case performance analysis
    • AI skill bottleneck detection
    • Workflow heatmaps
    • ConnectSoft AI agents can:

    • Attach additional tags at runtime

    • Generate observability dashboards
    • Trigger alerts or summaries using SK

โœ… Semantic Kernel planners may use metrics to optimize execution order


โœ… Summary

  • The template enables full-stack observability via OpenTelemetry
  • Traces, logs, and metrics are structured, tagged, and exportable
  • Works seamlessly with REST, gRPC, eventing, jobs, actors, and AI
  • Supports developer productivity, AI debugging, and enterprise monitoring

๐Ÿ” Configuration and Secrets Management

The template provides a secure, modular, and environment-aware configuration system, using:

  • ๐Ÿ” .NET's IOptions<T> pattern
  • ๐Ÿ” Integration with Azure Key Vault and Azure App Configuration
  • ๐Ÿ“ฆ Multi-environment config layering
  • โœ… Validation and defaults
  • ๐Ÿง  AI agent compatibility for dynamic reconfiguration

โš™๏ธ Configuration is centrally declared, strongly typed, and automatically validated on startup.


๐Ÿ“ฆ Core Project

Common/
โ””โ”€โ”€ MyService.Options/
    โ”œโ”€โ”€ JwtOptions.cs
    โ”œโ”€โ”€ ServiceBusOptions.cs
    โ”œโ”€โ”€ SemanticKernelOptions.cs
    โ”œโ”€โ”€ MongoDbOptions.cs
    โ”œโ”€โ”€ NhibernateOptions.cs
    โ””โ”€โ”€ ...

๐Ÿงฉ Supported Configuration Providers

Source Purpose
appsettings.{Environment}.json Local, per-environment config
Azure App Configuration Centralized key-value store (optional)
User Secrets Dev-only secret management
Azure Key Vault Secure, externalized secrets
Environment Variables Container/K8s overrides
Command Line Args Runtime config during launch

โš™๏ธ Template Parameters

Parameter Description
--AdditionalConfigurationProvider AzureAppConfiguration, None
--UseAuthentication Adds JwtOptions
--MessagingModelType Adds bus-specific options (e.g., RabbitMQ, ServiceBus)
--PersistenceModelType Adds SQL/Mongo connection options
--UseOpenAI Adds OpenAI and Semantic Kernel options
--UsePulumi Enables dynamic secrets from provisioned vault

๐Ÿงฑ IOptions Pattern with Validation

Each config section is bound to a typed POCO, registered with validation.

builder.Services
    .AddOptions<JwtOptions>()
    .Bind(configuration.GetSection("Jwt"))
    .ValidateDataAnnotations()
    .ValidateOnStart();

Example: JwtOptions.cs

public class JwtOptions
{
    [Required]
    public string Authority { get; set; }

    [Required]
    public string Audience { get; set; }
}

๐Ÿ”„ Environment Config Layering

appsettings.json
โ†ณ appsettings.Development.json
โ†ณ appsettings.Production.json
โ†ณ Environment Variables
โ†ณ secrets.json (dev only)
โ†ณ Azure App Config (optional)
โ†ณ Key Vault (optional)
  • โœ… Hierarchical override support
  • โœ… Safe for containerized deployments
  • โœ… Secrets never embedded in source code

๐Ÿ” Azure Key Vault Integration

If enabled:

  • Automatically resolves AzureKeyVault__Endpoint from environment
  • Injects secrets into configuration provider
  • Supports:

    • Connection strings
    • API keys
    • Tokens, passwords
    • OpenAI credentials
az keyvault secret set --vault-name my-vault --name Jwt--Authority --value https://login.example.com

โœ… Keys match config binding (e.g., Jwt:Authority)


๐Ÿ”‘ Azure App Configuration Integration

If --AdditionalConfigurationProvider AzureAppConfiguration:

  • Load all shared/global configs from App Config
  • Key filtering supported (Microservices:MyService:*)
  • Feature flags are synced from the same source

โœ… Easily update config across 100s of services


๐Ÿงช Validation and Fail-Fast Behavior

All IOptions<T> are validated at startup.

If required field is missing or malformed:

  • โŒ App fails to start
  • ๐Ÿ”Ž Error includes section name + failed validation reason
  • โœ… Ideal for CI/CD pipeline enforcement

๐Ÿง  Agent Use Cases

Agents can:

  • Generate .json or .yml configuration blocks
  • Inject secrets via az or Terraform commands
  • Toggle features dynamically via App Config
  • Securely request and rotate credentials from Key Vault

โœ… Semantic Kernel planners may react to config changes or feature toggles


๐Ÿงช Testing Strategy

Method Use
Unit tests for IOptions Validate config model binding
Secrets mocking Inject memory configuration source
AppSettings overrides Test per-environment behavior
AppConfig & Vault simulation Use Azure SDK test helpers

โœ… Summary

  • Config is modular, strongly typed, and secure
  • Fully supports:

    • Azure AppConfig
    • Azure Key Vault
    • IOptions pattern
    • Compatible with:

    • CI/CD

    • Kubernetes
    • Agentic and AI-driven systems

๐Ÿงฟ Feature Flags and Edition-Aware Behavior

The ConnectSoft Microservice Template supports dynamic feature toggling and edition-specific behavior using:

  • โœ… Microsoft.FeatureManagement (built-in to .NET)
  • โœ… Azure App Configuration integration
  • โœ… Tenant- and edition-aware evaluation
  • โœ… Declarative or code-based flag checks
  • โœ… AI agent compatibility for enabling/disabling features at runtime

๐ŸŽ› Feature flags allow services to conditionally activate functionality based on tenant, edition, stage, or experiment.


๐Ÿ“ฆ Core Project Involved

Common/
โ””โ”€โ”€ MyService.Options/
    โ””โ”€โ”€ FeatureManagement/
        โ””โ”€โ”€ FeatureFlagExtensions.cs

โš™๏ธ Template Parameters

Parameter Description
--FeatureFlags Enables feature management subsystem
--FeatureFlagsProvider AppSettings, AzureAppConfiguration
--UsePulumi Can provision initial flags in App Config
--UseSemanticKernel Allows planner-based feature activation
--UseMicrosoftBotBuilder Dialog steps can be gated by flags

๐Ÿงญ Feature Flags Model

Level Description
Global Affects all tenants/services
Tenant-Scoped Applies only to a tenant (X-Tenant-ID)
Edition-Scoped Tied to SaaS edition metadata (e.g., Free, Pro, Enterprise)
Stage-Based Dev/Test/Staging/Production rollout

Flags are defined as:

{
  "FeatureManagement": {
    "EnableChatbot": true,
    "EnableAuditTrail": false,
    "EnableSKPlanning": {
      "EnabledFor": [
        {
          "Name": "Tenant",
          "Parameters": { "TenantId": "tenant-xyz" }
        }
      ]
    }
  }
}

๐Ÿงฉ Sample Usage in Code

Conditional service registration:

services.AddFeatureFlagConditional<INotificationService, DefaultNotificationService>(
    feature: "EnableNotifications");

Use case filter:

if (!await _featureManager.IsEnabledAsync("EnableAuditTrail"))
    return;

Razor page or controller condition:

@if (await featureManager.IsEnabledAsync("EnableSemanticSkills"))
{
    <button>Use AI Assistant</button>
}

๐Ÿ›‚ Edition-Aware Behavior

Using EditionMetadata, a microservice can:

  • Check if a tenant is on a specific edition (e.g., Pro)
  • Gate features like:

    • Semantic search
    • API rate limits
    • Advanced insights
    • Real-time AI planner usage
if (_edition.Is("Enterprise") && await _feature.IsEnabledAsync("EnableRealtimeAI"))
{
    // Allow premium AI skill
}
  • โœ… EditionMetadata injected via header, token, or feature store
  • โœ… Can also be used in SK planner prompts

โ˜๏ธ Azure App Configuration Support

If --FeatureFlagsProvider AzureAppConfiguration:

  • Flags are synced in real-time
  • No need to restart service to apply flag changes
  • Supports:

    • Targeting filters
    • Rollout strategies
    • Key prefixing (MyService:*)
App Configuration Key: MyService:FeatureManagement:EnableBetaUI = true

โœ… Managed via Azure Portal or CI/CD tools (Pulumi, Terraform, az CLI)


๐Ÿงช Testing and Debugging

Method Tool
Feature toggle logic Unit test with in-memory feature provider
Edition rules Use mock tenant and edition metadata
AppConfig integration Use AzureAppConfigurationEmulator or local KV
Planner behavior Test planner prompt reactions to disabled skills

๐Ÿง  AI and Agent Usage

Agents can:

  • Discover active/inactive features dynamically
  • Enable experimental features during planning
  • Annotate SK prompts with active feature list
  • Roll out features to specific tenants/editions

โœ… Fully compatible with planner-based decisions โœ… Can be embedded in Bot dialogs, dashboards, skills


โœ… Summary

  • Feature toggling is declarative, scoped, and traceable
  • Supports tenant, edition, stage, and runtime toggles
  • Aligned with Azure App Config, Semantic Kernel, and agentic workflows
  • Drives experimentation, gradual rollout, and user-tiered functionality

โค๏ธโ€๐Ÿฉน Health Checks and Readiness Probes

Health checks ensure that services are:

  • Alive (running)
  • Ready (able to serve traffic)
  • Started (fully initialized)

The ConnectSoft Microservice Template includes built-in support for all three types of checks, fully aligned with:

  • ๐Ÿ”„ Kubernetes probes
  • โ˜๏ธ Azure App Service health ping
  • ๐Ÿงช Dev/Test monitoring
  • ๐Ÿ”Ž Observability systems (Prometheus, Application Insights)

๐Ÿ“ฆ Core Support

If --HealthCheck is enabled, the template auto-registers:

Endpoint Purpose Path
Liveness Is the process alive? /health/live
Readiness Is the service ready to receive traffic? /health/ready
Startup Has it finished initialization? /health/startup

๐Ÿ›ก๏ธ Endpoints are grouped under the built-in HealthChecks subsystem from ASP.NET Core.


โš™๏ธ Template Parameters

Parameter Description
--HealthCheck Enables core /health/* endpoints
--HealthCheckUI Adds optional dashboard (e.g., /health-ui)
--UsePulumi Deploys AppService with built-in ping config
--ServiceModelType Registers HTTP middleware in REST, gRPC, or Function host

๐Ÿฉบ Health Check Configuration

In Program.cs:

builder.Services.AddHealthChecks()
    .AddSqlServer(...)
    .AddMongoDb(...)
    .AddRedis(...)
    .AddMassTransit(...)
    .AddCheck<MyServiceCheck>("my_service_logic");

app.UseHealthChecks("/health/live", new HealthCheckOptions { Predicate = _ => false });
app.UseHealthChecks("/health/ready", new HealthCheckOptions { Predicate = hc => hc.Tags.Contains("ready") });

๐Ÿงฉ Tagged Health Checks

Each check is tagged for granular behavior:

Tag Description
live Process health (e.g., is Kestrel running?)
ready Readiness (e.g., DB connection, bus connectivity)
startup Cold start logic (e.g., migrations complete)

โœ… Allows individual endpoints to only include specific checks


๐Ÿงช Examples

services.AddHealthChecks()
    .AddMongoDb(connectionString, name: "Mongo", tags: new[] { "ready" })
    .AddCheck<MemoryUsageHealthCheck>("Memory", tags: new[] { "live" });

๐Ÿ”ฌ Custom Health Check Example

public class SemanticKernelHealthCheck : IHealthCheck
{
    public Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken token)
    {
        return Task.FromResult(HealthCheckResult.Healthy("SK initialized"));
    }
}

โœ… Register with .AddCheck<SemanticKernelHealthCheck>("SemanticKernel", tags: new[] { "ready" })


๐ŸŒ Kubernetes Probes Example

livenessProbe:
  httpGet:
    path: /health/live
    port: 80
  initialDelaySeconds: 5
  periodSeconds: 10

readinessProbe:
  httpGet:
    path: /health/ready
    port: 80
  initialDelaySeconds: 10
  periodSeconds: 5

๐Ÿ–ฅ๏ธ Health Check UI (Optional)

If --HealthCheckUI:

  • Hosted at /health-ui
  • Shows:

    • Last status
    • Duration
    • Failures
    • Supports multiple services (aggregate dashboard)

๐Ÿ“Š Metrics and Observability

Each check:

  • Adds span to OpenTelemetry trace
  • Contributes to /metrics for Prometheus:

    • health_check_duration_seconds
    • health_check_failures_total

โœ… Easily correlated with logs and alerts


๐Ÿง  AI & Agent Usage

Agents may:

  • Inject checks for:

    • AI skill registry health
    • Plugin API availability
    • Memory or token quota
    • Monitor readiness before deploying dependent systems
    • Use AI-driven planners to react to service health (e.g., retry, reroute, notify)

โœ… Skills and grains can expose custom check interfaces โœ… Future support: planner-based self-healing logic


โœ… Summary

  • The template includes modular, observable, and probe-ready health checks
  • Supports:

    • Live/readiness/startup probes
    • Custom application logic
    • Third-party dependencies
    • Aligns with:

    • Kubernetes

    • Azure App Service
    • DevOps alerts
    • AI agent workflows

๐Ÿ” Authentication, Authorization, and Multi-Tenancy

The ConnectSoft Microservice Template provides a secure and multi-tenant-ready architecture by integrating:

  • ๐Ÿ” OAuth2 / OpenID Connect authentication
  • ๐Ÿ›ก Role- and scope-based authorization
  • ๐ŸŒ Tenant-aware filtering and routing
  • ๐Ÿงฑ Middleware and attribute-based access control
  • ๐Ÿง  Compatibility with AI agent claims and tenant metadata

This ensures that every microservice is secure by default, yet extensible for complex SaaS needs.


โš™๏ธ Template Parameters

Parameter Description
--UseAuthentication Enables JWT bearer support
--UseMicrosoftBotBuilder Enables identity support in bot conversations
--ServiceModelType Required for REST/gRPC/SignalR auth integration
--UsePulumi Auto-provisions Azure App registrations and permissions
--UseFeatureFlags Can conditionally enable/disable per-tenant features

๐Ÿ” Authentication (JWT + OAuth2)

Built-in Integration With:

  • โœ… OpenIddict (default identity server)
  • โœ… Azure Active Directory
  • โœ… Custom OIDC providers (e.g., Auth0, IdentityServer4)

Key Middleware:

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.Authority = config["Jwt:Authority"];
        options.Audience = config["Jwt:Audience"];
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true
        };
    });

๐Ÿ“ฆ Bound to strongly-typed JwtOptions via IOptions<T>


๐Ÿ›ก Authorization

Authorization can be enforced via:

Technique Usage
[Authorize(Roles = "Admin")] Attribute-based
services.AddAuthorization(options => { ... }) Policy-based
.RequireScope("orders.read") Scope validation
IAuthorizationHandler Custom logic (e.g., per-tenant permissions)

โœ… Supports nested policies (e.g., "RequireAdminForTenant")


๐ŸŒ Multi-Tenancy Support

Each request is evaluated with a TenantContext, populated via:

  • ๐Ÿ”น X-Tenant-ID header
  • ๐Ÿ”น tenantId JWT claim
  • ๐Ÿ”น Bot dialog or actor context
  • ๐Ÿ”น Azure App Config for edition overrides

Middleware Auto-Registers:

app.UseTenantResolution();

โœ… Injected globally via ITenantContextAccessor โœ… Tenant ID is tagged in:

  • Logs
  • Traces
  • Events
  • Metrics
  • AI prompts

๐Ÿงฑ Role & Scope Mapping Example

{
  "sub": "user-123",
  "tenantId": "tenant-abc",
  "roles": ["Manager"],
  "scp": ["orders.read", "invoices.create"]
}

Mapped internally to:

  • ClaimsPrincipal roles
  • Policy handlers
  • Multi-tenant guards (e.g., restrict data access to user's tenant)

๐Ÿงช Testing Auth

Scenario Strategy
REST API with token Use mocked JWT via test token issuer
Tenant isolation Use alternate tenant ID claims or headers
Scope enforcement Add/remove scp claim and test policies
Bot auth Use Bot Emulator with OAuth flow
Actor + auth Test grain calls with tenant-mocked context

๐Ÿง  Agent and AI Integration

  • Agents can:

    • Create new OAuth clients in Pulumi
    • Assign user roles and scopes
    • Validate identity during Bot onboarding
    • Store tenant metadata in Semantic Kernel memory
    • SK skills can:

    • Require auth

    • Route data based on tenant
    • Auto-adjust prompts per edition level

โœ… Permissions are part of execution context in AI workflows โœ… Identity is compatible with planner decisions and feature gates


๐Ÿ“Œ Security Hardening Best Practices (Included)

  • โœ… HTTPS enforced via Kestrel or NGINX config
  • โœ… Rate limiting and IP filter stubs available
  • โœ… Token lifetime validation
  • โœ… CORS restricted per environment
  • โœ… Token propagation across message bus and job context

โœ… Summary

  • Built-in authentication and authorization
  • Multi-tenant and edition-aware logic
  • Compatible with:

    • REST/gRPC/Bot/SignalR
    • Events, actors, and AI
    • Secure defaults, extensibility points, and CI/CD support
    • Ideal for SaaS, enterprise, and federated scenarios

๐Ÿ”„ Background Jobs and Retry Mechanics

The ConnectSoft Microservice Template includes modular support for background job execution, enabling microservices to:

  • Run asynchronous and delayed tasks
  • Process long-running or scheduled jobs
  • Ensure reliability through retries, timeouts, and fallbacks
  • Scale job processing across distributed nodes
  • Integrate with Hangfire, Quartz, Azure Functions, and Polly

โš™๏ธ Designed for resilience, observability, and composability, job execution is wired through clearly separated scheduler models.


๐Ÿ“ฆ Job Execution Models

Scheduler Project Description
Hangfire SchedulerModel.Hangfire Background job runner with dashboard, CRON, and retries
Quartz.NET SchedulerModel.Quartz Durable job scheduling, clustering support
Azure Functions ServiceModel.AzureFunction Timer-based serverless jobs (if selected)

โš™๏ธ Template Parameters

Parameter Description
--SchedulerModelType Hangfire, Quartz, or None
--UseOpenAI / --UseSemanticKernel Allows jobs to trigger AI skills
--UsePulumi Deploys job runtime containers or schedules
--MessagingModelType Enables background command queues or worker subscribers
--UseHangfireDashboard Exposes dashboard at /hangfire (auth required)

๐Ÿง  Job Class Structure (Hangfire Example)

public class ProcessInvoiceJob : IBackgroundJob
{
    public async Task ExecuteAsync(CancellationToken cancellationToken)
    {
        // Call use case, actor, or message bus
    }
}

Registered in HangfireJobRegistry.cs:

RecurringJob.AddOrUpdate<ProcessInvoiceJob>(
    job => job.ExecuteAsync(CancellationToken.None),
    Cron.Daily);

โœ… Fluent or CRON syntax โœ… Retry and exponential backoff supported automatically


๐Ÿ” Retry and Fallback Patterns

The template uses Polly internally to provide:

Pattern Description
Retry Retry on failure N times
CircuitBreaker Open circuit after N failures
Timeout Cancel long-running execution
Fallback Recover gracefully when all else fails

Example

var policy = Policy
    .Handle<TransientException>()
    .RetryAsync(3);

await policy.ExecuteAsync(() => handler.ExecuteAsync(request));

โœ… Polly is included for:

  • Job handlers
  • Message consumers
  • Use case orchestrators

๐Ÿ“Š Observability in Jobs

  • โœ… All jobs are traced via OpenTelemetry spans
  • โœ… Metrics exposed:

    • background_job_duration_seconds
    • job_failures_total
    • job_queue_depth
    • โœ… Job name, tenant ID, and correlation ID auto-tagged

๐Ÿงช Testing Background Logic

Concern Strategy
Job logic Test with DI-injected mocks and unit tests
Retry Simulate transient failures
Hangfire Use in-memory storage, assert scheduling
Quartz Assert trigger state and misfire recovery

โœ… Retry logic tested with injected FakePolicy โœ… Time manipulation via SystemClock.Override


๐Ÿง  AI Job Use Cases

  • Schedule daily summary reports from AI
  • Run SK-powered semantic workflows every X hours
  • Retry knowledge ingestion on failure
  • Periodically refresh embeddings or documents
  • Auto-invoke BotFramework proactive messages

โœ… AI skills used as job entrypoints or steps โœ… Skills can trigger commands, log insight, or dispatch messages


๐Ÿงญ Integration Points

  • โœ… Can dispatch domain events
  • โœ… Can execute use case handlers
  • โœ… Can call APIs or publish messages
  • โœ… Can be triggered via webhooks, events, or schedules

๐Ÿ”’ Security and Isolation

  • Jobs execute under:

    • Assigned TenantId (injected into context)
    • Scoped lifetime and execution ID
    • Dashboard access (Hangfire): protected via [Authorize]
    • Failures: auto-logged, retried, and pushed to dead-letter storage (if bus enabled)

โœ… Summary

  • Fully supports resilient background processing
  • Retry, fallback, and timeouts via Polly
  • Composable with:

    • Message bus
    • Domain model
    • AI skills
    • Observable, secure, and multi-tenant aware
    • Scheduler pluggable: Hangfire, Quartz, Azure Functions

๐Ÿณ Docker, Compose, and Containerization

The ConnectSoft Microservice Template is designed with cloud-native, container-first principles, enabling:

  • Local development using Docker Compose
  • Cloud deployment to Kubernetes or App Services
  • Integration with CI/CD pipelines and Azure Container Registry
  • Seamless developer onboarding with reproducible environments

๐Ÿณ Every service is generated with fully working containerization support โ€” including Dockerfiles, compose manifests, and readiness probes.


๐Ÿ“ฆ Core Structure

Infrastructure/
โ””โ”€โ”€ DockerCompose/
    โ”œโ”€โ”€ docker-compose.yml
    โ”œโ”€โ”€ .env
    โ””โ”€โ”€ docker-compose.override.yml

Application/
โ””โ”€โ”€ MyService.Application/
    โ””โ”€โ”€ Dockerfile

โš™๏ธ Template Parameters

Parameter Description
--Docker Enables Dockerfile generation and Docker Compose support
--UsePulumi Generates container registry provisioning and tagging
--UseOpenTelemetry Exposes /metrics and tracing endpoints
--HealthCheck Adds health probes to compose and Dockerfile
--HttpPort / --HttpsPort Allows port mapping customization

๐Ÿ› ๏ธ Dockerfile Example (App Host)

FROM mcr.microsoft.com/dotnet/aspnet:8.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:8.0 AS build
WORKDIR /src
COPY . .
RUN dotnet publish "MyService.Application.csproj" -c Release -o /app/publish

FROM base AS final
WORKDIR /app
COPY --from=build /app/publish .
ENTRYPOINT ["dotnet", "MyService.Application.dll"]
  • โœ… Supports multi-stage build
  • โœ… Optimized for ACR push and Kubernetes usage
  • โœ… Automatically includes .env and health probe support

๐Ÿงช docker-compose.yml

version: '3.9'
services:
  myservice:
    build:
      context: .
      dockerfile: Application/MyService.Application/Dockerfile
    ports:
      - "5000:80"
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - DOTNET_RUNNING_IN_CONTAINER=true
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost/health/ready"]
      interval: 10s
      timeout: 5s
      retries: 3

โœ… Auto-configured for:

  • Local HTTPS
  • Hot reload
  • Environment overrides

๐ŸŒ Port Mapping

Host Port Container
5000 http://localhost (default REST API)
5001 https://localhost (if enabled)
9090 /metrics, Prometheus
8080 Bot framework endpoint
6379 Redis sidecar (if enabled)

๐Ÿง  Runtime Containers Supported

Container Type Used For
Service Host Primary REST/gRPC/API service
Worker Host Background jobs and consumers
Bot Host Microsoft Bot Framework
Dapr Sidecar Actor support, bindings, pub/sub
Telemetry Agent OpenTelemetry Collector or Application Insights
PostgreSQL/SQL Server Local DB testing
MongoDB NoSQL scenarios
Redis Caching, state, actor timer storage

๐Ÿ“ฆ Build Targets

Context Target
Local Dev docker-compose up --build
Azure DevOps docker build . && docker push
Pulumi IaC Pulumi.Azure.ContainerApp(...)
Helm Chart Ready-to-deploy for AKS / EKS

๐Ÿงช Testing and Debugging

  • Use Visual Studio Container Tools or VSCode Remote Containers
  • Includes debug-ready profiles in launchSettings.json
  • Health checks verified via /health/* endpoints
  • Logs exposed via stdout (structured JSON for Serilog)

๐Ÿ” Security & Secrets in Docker

  • Supports:

    • .env injection for local secrets
    • Azure Key Vault volume mounting (Kubernetes)
    • Secret store or vault integration via Pulumi

โœ… Never hardcodes secrets into Docker images โœ… Production config uses ASPNETCORE_ENVIRONMENT and per-container override


๐Ÿง  Agent Compatibility

Agents can:

  • Generate container builds in CI
  • Push to registry (ACR, GHCR, DockerHub)
  • Update Docker Compose files
  • Trigger semantic flows via container metadata
  • Auto-generate Helm or YAML manifests for each containerized microservice

โœ… Summary

  • Container-first design using multi-stage Dockerfiles
  • Includes Docker Compose for local testing
  • Supports health checks, environment configs, and observability ports
  • Ready for:

    • CI/CD
    • Kubernetes
    • Developer sandbox environments
    • Used by both developers and ConnectSoft agents

โ˜ธ๏ธ Kubernetes and Helm Deployment Support

The ConnectSoft Microservice Template is designed for Kubernetes-first deployments, providing:

  • ๐Ÿงฑ Minimal and extensible YAML manifests
  • ๐ŸŽ› Configurable Helm chart templates
  • ๐Ÿ“ฆ Container lifecycle hooks and health probes
  • ๐Ÿ” Secure secret management
  • ๐Ÿ”„ Integration with Pulumi, Azure AKS, and CI/CD pipelines

โ˜๏ธ Kubernetes support ensures every microservice can scale, self-heal, and integrate in a cloud-native cluster.


๐Ÿ“ฆ Included Artifacts

If --Docker and --UsePulumi are selected, the template generates:

Infrastructure/
โ””โ”€โ”€ Kubernetes/
    โ”œโ”€โ”€ base/
    โ”‚   โ”œโ”€โ”€ deployment.yaml
    โ”‚   โ”œโ”€โ”€ service.yaml
    โ”‚   โ”œโ”€โ”€ ingress.yaml
    โ”‚   โ””โ”€โ”€ secret.yaml
    โ””โ”€โ”€ helm/
        โ”œโ”€โ”€ Chart.yaml
        โ”œโ”€โ”€ values.yaml
        โ””โ”€โ”€ templates/

โš™๏ธ Deployment Configuration

File Purpose
deployment.yaml Defines container spec, env, volumes, probes
service.yaml Exposes app via ClusterIP, LoadBalancer, or NodePort
ingress.yaml Adds optional routing via NGINX, Traefik, Istio
secret.yaml Injects config via mounted secret or env var
values.yaml Parameterizes Helm chart values
Chart.yaml Helm chart metadata for packaging

๐Ÿงฉ Key Features Supported

Feature Description
โœ… Liveness/Readiness probes /health/live, /health/ready
โœ… Rolling updates readinessGate, rollingUpdate
โœ… CPU/Memory limits Defined in values.yaml
โœ… TLS + Ingress With optional cert-manager annotations
โœ… Sidecars Dapr, OpenTelemetry, or logging sidecars included
โœ… Affinity & NodeSelector Optional anti-affinity rules
โœ… Service Mesh Istio/Linkerd compatibility (labels and annotations ready)

๐Ÿ“ Example Deployment Snippet

apiVersion: apps/v1
kind: Deployment
metadata:
  name: myservice
spec:
  replicas: 3
  selector:
    matchLabels:
      app: myservice
  template:
    metadata:
      labels:
        app: myservice
    spec:
      containers:
        - name: myservice
          image: myregistry.azurecr.io/myservice:1.0.0
          ports:
            - containerPort: 80
          livenessProbe:
            httpGet:
              path: /health/live
              port: 80
          readinessProbe:
            httpGet:
              path: /health/ready
              port: 80

๐Ÿงช Helm Chart Structure

File Purpose
templates/deployment.yaml Templated Kubernetes deployment
values.yaml Defines:
  • replicaCount
  • image.repository
  • env, resources, ingress | | Chart.yaml | Chart metadata | | templates/service.yaml | ClusterIP service | | templates/ingress.yaml | Optional HTTP routing |

โœ… Supports CI/CD deployment via:

helm upgrade --install myservice ./helm --values values.prod.yaml

๐Ÿ” Secrets and Config Management

Method Description
envFrom: secretRef Mounts secret directly into container
Azure Key Vault Injected via CSI driver
configMap Mounts appsettings or values.yaml overrides

Secrets never stored in Git; injected via secure pipeline


๐Ÿง  Pulumi/Kubernetes Integration

If --UsePulumi is true:

  • Kubernetes manifests are provisioned using Pulumi YAML or TS
  • ACR registry image is published, tagged, and deployed
  • Environment-specific values are stored in stack configs

โœ… Compatible with AKS, EKS, GKE, Minikube


๐Ÿง  Agent Usage and Automation

Agents can:

  • Update deployment replica count
  • Inject secrets during rollout
  • Monitor readiness via /health/ready
  • Execute rolling deployments with semantic change annotations
  • Trigger Helm chart generation dynamically

โœ… Helm chart metadata includes semantic tags (e.g., version, role, edition)


๐Ÿ“Š Observability with K8s

  • Health probes surface into:

    • Prometheus scrape targets
    • Azure App Insights
    • Container logs collected via:

    • FluentBit

    • OpenTelemetry sidecars
    • Loki/Grafana stack

โœ… Summary

  • Fully prepared for Kubernetes deployment using:

    • Base YAMLs
    • Helm charts
    • CI/CD pipeline support
    • Includes:

    • Readiness probes

    • Secrets/config handling
    • Sidecar and service mesh integration
    • Compatible with:

    • Agents

    • Pulumi
    • Azure DevOps, GitHub Actions

๐Ÿ—๏ธ Infrastructure as Code with Pulumi

The ConnectSoft Microservice Template optionally generates a complete Infrastructure as Code (IaC) project using Pulumi to:

  • Provision cloud-native resources for each microservice
  • Enable repeatable, automated environments (dev/staging/prod)
  • Integrate infrastructure into CI/CD workflows
  • Support both Azure and multi-cloud platforms

๐Ÿงฑ Pulumi is chosen for its modern language-first approach, modularity, and strong integration with Azure, Kubernetes, and container registries.


๐Ÿ“ฆ Project Structure

Infrastructure/
โ””โ”€โ”€ Pulumi/
    โ”œโ”€โ”€ Pulumi.yaml
    โ”œโ”€โ”€ Pulumi.dev.yaml
    โ”œโ”€โ”€ index.ts
    โ”œโ”€โ”€ azure/
    โ”‚   โ”œโ”€โ”€ appservice.ts
    โ”‚   โ”œโ”€โ”€ containerregistry.ts
    โ”‚   โ”œโ”€โ”€ keyvault.ts
    โ”‚   โ”œโ”€โ”€ servicebus.ts
    โ”‚   โ”œโ”€โ”€ cosmosdb.ts
    โ”‚   โ””โ”€โ”€ monitoring.ts

โœ… Each service template gets its own isolated Pulumi stack with environment support.


โš™๏ธ Template Parameters

Parameter Description
--UsePulumi Adds Pulumi IaC project
--UseApplicationInsights Deploys Azure Monitor with correlation ID tagging
--UseAuthentication Registers App Registration and OIDC app
--MessagingModelType Provisions RabbitMQ, Azure Service Bus, or topic queues
--PersistenceModelType Deploys SQL, CosmosDB, or MongoDB instance
--UseOpenAI Creates Azure OpenAI service or secret linkages
--Docker Builds and pushes Docker image to ACR as part of the stack

๐Ÿš€ Pulumi Resource Modules

Module Description
containerregistry.ts Creates ACR registry + access credentials
appservice.ts Azure Web App / Container App for the service host
servicebus.ts Topic, queue, and namespace provisioning
cosmosdb.ts Database account and containers
keyvault.ts Secure secret storage and identity injection
monitoring.ts App Insights, Log Analytics, and telemetry wiring
dns.ts Optional DNS A/CNAME records and certs

๐Ÿงฌ Example: Provisioned Stack

const app = new azure.appservice.ContainerApp("myservice", {
    resourceGroupName,
    image: "myregistry.azurecr.io/myservice:1.0.0",
    ingress: { external: true },
    environmentVariables: {
        "ASPNETCORE_ENVIRONMENT": "Production",
        "Jwt__Authority": keyVault.getSecret("Jwt__Authority")
    }
});

โœ… All secrets loaded via Key Vault binding โœ… Output values are published to .env, Pulumi.dev.yaml, or Azure App Config


๐Ÿ›ก๏ธ Secrets & Identity

  • Secrets like:

    • Jwt__Authority
    • ServiceBus__ConnectionString
    • OpenAI__ApiKey
    • Are stored in:

    • Pulumi secret config

    • Azure Key Vault
    • Kubernetes secrets (if applicable)

๐Ÿง  Multi-Stack and Environment Support

File Description
Pulumi.dev.yaml Dev configuration
Pulumi.staging.yaml Stage/pre-prod config
Pulumi.prod.yaml Production configuration
Pulumi.yaml Stack metadata and backend settings

โœ… Fully supports environment separation via pulumi stack select โœ… Compatible with GitHub Actions and Azure DevOps Pipelines


๐Ÿงช Testing and Preview

  • pulumi preview โ€“ dry-run the deployment
  • pulumi up โ€“ deploy changes to cloud
  • pulumi destroy โ€“ tear down service and all dependencies

โœ… Safe, observable, and auditable


๐Ÿง  Agent Usage

ConnectSoft AI agents can:

  • Extend or regenerate Pulumi modules
  • Read provisioned outputs as environment inputs for apps
  • Generate .env or launchSettings.json with secrets
  • Use tags, annotations, and labels for planner optimization
  • Auto-bind DNS records and certificates via IaC

โœ… Full traceability between code, infrastructure, and execution context


๐Ÿ”„ CI/CD Integration

Tool Step
Azure DevOps Pulumi CLI task or bash inline script
GitHub Actions Pulumi Action + Azure login
Pulumi Cloud Observability, auditing, access controls

โœ… Summary

  • Full infrastructure automation with Pulumi
  • Generates Azure resources based on selected options
  • Supports:

    • ACR
    • App Service
    • Service Bus
    • Key Vault
    • CosmosDB
    • App Config
    • Enables secure, repeatable, observable deployments

๐Ÿš€ CI/CD Pipelines and DevOps Integration

The ConnectSoft Microservice Template includes built-in support for automated delivery pipelines, aligned with:

  • ๐Ÿ“ฆ Azure DevOps
  • ๐Ÿ” GitHub Actions
  • ๐Ÿณ Container-based build and release
  • ๐Ÿงช Full test, lint, validate, and deploy flow
  • ๐Ÿง  Agent-driven orchestration (pipeline-as-code)

๐Ÿงฉ Pipelines are designed to support multi-project solutions, multiple environments, and template-generated services at scale.


๐Ÿ“‚ Pipeline Artifacts Included

Infrastructure/
โ””โ”€โ”€ Pipelines/
    โ”œโ”€โ”€ azure-devops/
    โ”‚   โ”œโ”€โ”€ ci.yml
    โ”‚   โ”œโ”€โ”€ cd.yml
    โ”œโ”€โ”€ github-actions/
    โ”‚   โ”œโ”€โ”€ ci.yml
    โ”‚   โ”œโ”€โ”€ release.yml
    โ”œโ”€โ”€ templates/
    โ”‚   โ”œโ”€โ”€ dotnet-build.yml
    โ”‚   โ”œโ”€โ”€ docker-build.yml
    โ”‚   โ””โ”€โ”€ pulumi-deploy.yml

โš™๏ธ Template Parameters

Parameter Description
--Docker Enables containerized builds and push stages
--UsePulumi Includes Pulumi-based deploy stages
--UseFeatureFlags Syncs flags with Azure App Configuration
--MessagingModelType Adds infrastructure targets (e.g., RabbitMQ, Service Bus)
--UseOpenTelemetry Adds trace publishing and exporter hooks
--UseApplicationInsights Adds instrumentation output to App Insights
--UseUnitTests Registers test discovery, coverage, and validation

๐Ÿงช CI Pipeline Stages (ci.yml)

Stage Description
Checkout Clones repo, validates Git state
Build Runs dotnet build and/or Docker build
Test Runs unit + integration tests
Lint Code format, dependency check
Analyze Optional SonarQube or Roslyn rules
Pack Packages NuGet outputs (if any)
Publish Artifacts .nupkg, coverage reports, logs

โœ… Fully isolated with per-project build/test matrix


๐Ÿš€ CD Pipeline Stages (cd.yml)

Stage Description
Pull Image Pulls image or artifact from registry
Pulumi Deploy Provisions cloud infrastructure
Helm Deploy (Optional) Deploy to Kubernetes
Post-Deploy Health Polls /health/ready endpoint
Slack/Teams Notify Sends result to release channels

โœ… Can include multi-environment gate (e.g., dev โ†’ staging โ†’ prod) โœ… Compatible with service mesh, scaling rules, and rollout policies


๐Ÿงช Testing Pipeline Integration

Framework Included
MSTest โœ…
SpecFlow (BDD) โœ…
xUnit (optional) โฌœ๏ธ
Coverlet Coverage โœ… Output to Cobertura/LCOV
Architecture Tests โœ… Rules for layering, cyclic dependencies

๐Ÿ“ Results are exported to Azure DevOps test tab or GitHub Actions artifacts.


๐Ÿ“ฆ Docker Registry Integration

Registry Integration
Azure Container Registry (ACR) az acr login and docker push
GitHub Container Registry (GHCR) Auth via GitHub token
DockerHub Env-based login and tagging

Tags typically follow:

myservice:1.0.0
myservice:2024.05.01-ci.1234

๐Ÿ” Secrets and Key Vault

  • Azure DevOps uses Key Vault Task to fetch secrets at runtime
  • GitHub Actions can:

    • Use environment secrets
    • Pull secrets via Pulumi stack config

๐Ÿง  AI Agent and Planner Integration

Agents can:

  • Inject pipeline variables or override task inputs
  • Trigger builds/releases via GitHub/DevOps APIs
  • Analyze failed builds and suggest corrections
  • Attach semantic metadata to pipeline runs (e.g., tags like ai-generated)
  • Generate post-run summaries or adaptive cards

โœ… Used in continuous planning loops โœ… Skills and plugins map to each DevOps phase


โœ… Summary

  • CI/CD pipelines for build, test, package, deploy
  • Supports:

    • Azure DevOps
    • GitHub Actions
    • Pulumi + Helm + Docker
    • Fully traceable, testable, and agent-aware
    • Enables safe, scalable, and observable software delivery

๐Ÿงช Unit Testing, BDD, and Quality Gates

The ConnectSoft Microservice Template promotes test-first, specification-driven development, and includes:

  • โœ… Unit tests for logic isolation
  • โœ… BDD tests using SpecFlow for behavior verification
  • โœ… Architecture rules for Clean Architecture enforcement
  • โœ… Test coverage metrics with reporting integration
  • โœ… CI-compatible quality gates (optional)

๐Ÿง  Testing infrastructure is designed to be automatable, AI-analyzable, and pipeline-ready.


๐Ÿ“‚ Test Project Structure

Testing/
โ”œโ”€โ”€ UnitTests/
โ”‚   โ””โ”€โ”€ Domain/
โ”‚   โ””โ”€โ”€ Application/
โ”œโ”€โ”€ AcceptanceTests/
โ”‚   โ””โ”€โ”€ Features/
โ”‚   โ””โ”€โ”€ Steps/
โ”‚   โ””โ”€โ”€ Hooks/
โ”œโ”€โ”€ ArchitectureTests/
โ”‚   โ””โ”€โ”€ LayerRules/
โ”‚   โ””โ”€โ”€ DependencyGuards/

Each testing layer targets different responsibilities:

  • UnitTests โ†’ logic correctness
  • AcceptanceTests โ†’ feature specs (BDD)
  • ArchitectureTests โ†’ project structure & design discipline

๐Ÿงช Unit Tests (MSTest)

Examples:

  • Aggregate behavior (e.g., Order.Place() changes state)
  • Use case logic
  • Value object equality
  • Validators with edge cases

โœ… Uses MSTest.TestFramework by default (can switch to xUnit/NUnit)


โœ… FluentValidation Test Integration

var validator = new CreateOrderValidator();
var result = validator.TestValidate(input);
result.ShouldHaveValidationErrorFor(x => x.CustomerId);

๐Ÿ“– BDD Testing with SpecFlow

  • Included via AcceptanceTests project
  • SpecFlow used for:

    • Domain workflows
    • Event-driven scenarios
    • End-to-end tests via REST/gRPC/Bot calls

Feature File Example:

Feature: Order Placement

Scenario: Place a new order
  Given the customer is registered
  And they add an item to the cart
  When they submit the order
  Then the order should be saved
  And an OrderPlacedEvent should be published

Step Definition:

[When(@"they submit the order")]
public async Task WhenTheySubmitOrder()
{
    var result = await _client.PostAsync("/api/orders", ...);
    result.EnsureSuccessStatusCode();
}

โœ… Includes database fixture and test server for HTTP requests


๐Ÿงฉ Architecture Tests

Using NetArchTest.Rules:

  • Enforces:

    • No references from Infrastructure โ†’ Domain
    • Only Application can depend on DomainModel
    • Projects match clean layering structure

Example:

Types.InAssembly(ApplicationAssembly)
  .Should()
  .NotHaveDependencyOn("InfrastructureModel")
  .Check()
  .IsSuccessful.Should().BeTrue();

๐Ÿ“Š Code Coverage

  • Collected via coverlet.collector
  • Exported in CI as:

    • Cobertura (Azure DevOps)
    • LCOV (GitHub Actions)
    • Visualized in:

    • ReportGenerator

    • Azure DevOps Test Tab
    • SonarCloud (optional)

โœ… Thresholds can be enforced (e.g., 80% min per project)


๐Ÿง  Quality Gates (Optional)

Tool Role
SonarQube / SonarCloud Coverage + duplicate code + complexity
Mutation Testing Stryker.NET integration
Test Impact Analysis Azure DevOps or GitHub caching
Security Scans Optional static analysis (e.g., CredScan)

๐Ÿง  Agent Integration

  • Agents can:

    • Create new unit tests based on use cases
    • Generate .feature files from domain model
    • Analyze test failures and recommend fixes
    • Summarize test coverage gaps
    • Identify critical paths for regression testing
    • Inject tracing spans into test execution

โœ… Test output is tagged with correlation ID, tenant ID, trace ID


โœ… Summary

  • Full suite of automated tests:

    • Unit
    • BDD (SpecFlow)
    • Architecture
    • Coverage
    • Aligns with CI/CD and AI observability
    • Ensures code correctness, design discipline, and business alignment

๐Ÿ“š Structured Logging and Telemetry Enrichment

The ConnectSoft Microservice Template includes a structured, context-aware logging system designed to support:

  • โœ… Consistent and machine-readable log entries
  • ๐Ÿงญ Correlation of logs with traces and metrics
  • ๐Ÿ“ก Multi-tenant and multi-service observability
  • ๐Ÿ” Automatic enrichment with execution context
  • ๐Ÿ“ฅ Seamless integration with CI, AI agents, and distributed systems

๐Ÿ“˜ Logging is not just diagnostic โ€” it is a source of truth for runtime decisions, telemetry, and auditing.


โš™๏ธ Template Parameters

Parameter Description
--Logging Serilog (default), Log4Net, or None
--OpenTelemetry Enables trace ID correlation in logs
--UseApplicationInsights Routes logs to Azure Monitor
--UseAuditNet Optional audit logging stream
--UsePulumi Automatically configures sink per environment

โœ… Default Logging Pipeline (Serilog)

Key Features:

  • โœ… JSON-formatted logs
  • โœ… Console + file + remote sink support
  • โœ… Enriched with:

    • TenantId
    • CorrelationId
    • TraceId
    • UseCaseName
    • Environment

๐Ÿ“‚ Logging Configuration Example

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
      }
    },
    "Enrich": [ "FromLogContext", "WithThreadId", "WithMachineName" ],
    "WriteTo": [
      { "Name": "Console" },
      { "Name": "File", "Args": { "path": "Logs/log.json", "rollingInterval": "Day" } }
    ]
  }
}

โœ… Automatically injected via HostBuilderExtensions


๐Ÿงช Logging Example

{
  "timestamp": "2025-05-02T12:34:56Z",
  "level": "Information",
  "message": "Placing order {OrderId}",
  "orderId": "ORD-123",
  "correlationId": "ac3f4e18",
  "traceId": "00-abc123...",
  "tenantId": "tenant-x",
  "useCase": "PlaceOrder"
}

โœ… Ready for indexing in:

  • Elasticsearch
  • Seq
  • Azure Monitor
  • Grafana Loki

๐Ÿง  Logging Enrichers

The template adds enrichers automatically for:

Enricher Source
CorrelationId X-Correlation-ID or traceparent
TraceId OpenTelemetry span context
TenantId Resolved via TenantContext
UseCaseName Captured via pipeline execution metadata
Environment From ASPNETCORE_ENVIRONMENT

๐Ÿ”Œ Supported Sinks

Sink Status
Console โœ… Included by default
File (Rolling) โœ… JSON format logs
Azure Monitor โœ… With --UseApplicationInsights
OpenTelemetry Exporter โœ… For trace-log integration
Elasticsearch / Seq / Loki ๐Ÿ”„ Optional, easily added via DI container

๐Ÿ“ Log Levels

Level Use Case
Verbose Debugging local development only
Information Business-level operations (e.g., Order placed)
Warning Retryable failures, fallback paths
Error Unhandled exceptions, failed validation
Fatal Startup errors, critical pipeline breakage

๐Ÿงช Testing Strategy

  • Validate structured output using:

    • Serilog.TestLogger
    • Console snapshot matching
    • Log context assertion helpers
    • BDD: capture logs in SpecFlow ScenarioContext
    • Integration: assert logs appear in expected sink

๐Ÿง  Agent Capabilities

Agents can:

  • Inject or suggest new log events
  • Correlate logs with trace data
  • Generate summaries of past executions
  • Query logs for insights or triggers
  • Translate logs into adaptive cards (for bots or dashboards)

โœ… SK plugins can consume log data directly as part of memory or prompt input


โœ… Summary

  • Logging is structured, context-aware, and multi-sink ready
  • Fully aligned with:

    • Correlation IDs
    • Tenant metadata
    • AI and telemetry workflows
    • Enables real-time debugging, postmortem analysis, and intelligent orchestration

๐Ÿ”Œ Integration Abstractions and Extensibility Points

The ConnectSoft Microservice Template provides a clean, composable, and abstracted integration layer that enables microservices to:

  • Connect to external systems (e.g., APIs, CRMs, payment providers)
  • Publish and consume integration events
  • Add or swap adapters without changing core business logic
  • Register client/service abstractions as reusable modules
  • Enable AI agents to extend integrations dynamically

๐Ÿงฉ Integration logic is modular, resides outside the domain, and is wired through standard interfaces and dependency injection.


๐Ÿ“ฆ Core Integration Projects

Infrastructure/
โ”œโ”€โ”€ ExternalApis/
โ”‚   โ”œโ”€โ”€ Braze/
โ”‚   โ”œโ”€โ”€ Segment/
โ”‚   โ””โ”€โ”€ Stripe/
โ”œโ”€โ”€ Connectors/
โ”‚   โ”œโ”€โ”€ IHttpApiClient<TRequest, TResponse>
โ”‚   โ”œโ”€โ”€ IMessageDispatcher
โ”‚   โ””โ”€โ”€ IIntegrationPublisher

โœ… Used by both humans and agents to integrate cleanly with external systems.


๐Ÿงฑ Key Abstractions Provided

Interface Role
IHttpApiClient<TRequest, TResponse> General-purpose typed HTTP integration
IIntegrationPublisher Event dispatch abstraction (e.g., webhook, queue, third-party)
IMessageDispatcher Command dispatcher for decoupled use cases
INotificationDispatcher Email/SMS/push abstraction for alerts
IExternalServiceClient Marker interface for API wrappers

๐Ÿงฉ Example: API Client Abstraction

public interface IBrazeClient
{
    Task SendUserProfileAsync(BrazeProfileRequest request, CancellationToken ct);
}

Registered via:

services.AddHttpClient<IBrazeClient, BrazeClient>()
        .AddPolicyHandler(ResiliencePolicies.WithRetry());

โœ… Allows runtime configuration via IOptions<BrazeOptions> โœ… Can be mocked, tested, and traced


๐Ÿ› ๏ธ Connector Pattern for External APIs

public class StripePaymentConnector : IPaymentGateway
{
    public Task<PaymentResult> ChargeAsync(PaymentRequest request)
    {
        // Stripe SDK or HTTP client logic
    }
}

Registered via:

services.AddScoped<IPaymentGateway, StripePaymentConnector>();

โœ… Supports feature-driven swapping (e.g., replace Stripe with PayPal) โœ… Fully compatible with semantic AI agents


๐Ÿ” Message Dispatching & Integration Events

  • Integration events published via IIntegrationPublisher
  • Optional outbox pattern if using message bus
  • Webhook patterns also supported
await _integrationPublisher.PublishAsync(new AppointmentConfirmedEvent(...));

๐Ÿ“ฌ Notification Dispatcher

await _notificationDispatcher.SendAsync(new NotificationPayload
{
    Type = NotificationType.Email,
    To = user.Email,
    TemplateId = "welcome-template",
    Data = new { FirstName = user.FirstName }
});

โœ… Plug into:

  • SendGrid
  • MailKit
  • Twilio
  • Push Notification APIs

๐Ÿง  AI Agent and Planner Integration

  • Agents can:

    • Register new integration clients
    • Add connector metadata and test scaffolds
    • Use adapters as callable skills via Semantic Kernel
    • Wrap connectors with tracing, retries, and circuit breakers

โœ… All connectors implement trace-friendly interfaces and support observability hooks


๐Ÿงช Testability & Isolation

  • Interfaces injected via DI
  • Use WireMock, MockHttp, or FakeConnector
  • Supported by unit tests, BDD steps, and SK simulations

๐Ÿ“Š Observability

All integrations are:

  • Traced with OpenTelemetry spans
  • Logged using correlation ID and tenant metadata
  • Measured via custom metrics like:

    • external_api_calls_total
    • integration_failures_total

โœ… Summary

  • Provides extensible integration layer with clearly separated concerns
  • Supports:

    • External APIs
    • Messaging gateways
    • Notification systems
    • Enables:

    • Testability

    • Observability
    • Agent orchestration
    • Ideal for connectors, CRM integrations, and AI-triggered workflows

๐Ÿ“ Documentation with MkDocs and Mermaid Diagrams

The ConnectSoft Microservice Template includes first-class documentation support using:

  • ๐Ÿ“š MkDocs + Material for MkDocs
  • ๐Ÿง  Mermaid diagrams-as-code
  • ๐Ÿ—‚ Agent- and human-readable structure
  • ๐Ÿ” Auto-generated structure aligned with Clean Architecture and DDD

๐Ÿ“˜ Every generated service includes prebuilt, expandable documentation that scales with the project and supports autonomous agent navigation.


๐Ÿ“ฆ Documentation Files

docs/
โ”œโ”€โ”€ index.md
โ”œโ”€โ”€ architecture.md
โ”œโ”€โ”€ domain-model.md
โ”œโ”€โ”€ use-cases.md
โ”œโ”€โ”€ configuration.md
โ”œโ”€โ”€ messaging.md
โ”œโ”€โ”€ observability.md
โ””โ”€โ”€ diagrams/
    โ”œโ”€โ”€ domain-sequence.mmd
    โ””โ”€โ”€ architecture-structure.mmd

โœ… Follows the same format as the main ConnectSoft platform docs.


โš™๏ธ Template Parameters

Parameter Description
--UseDocumentation Enables documentation scaffold
--UsePulumi Includes infra diagrams and deployment flows
--UseOpenTelemetry Adds observability diagrams and spans
--ActorModelType Adds actor flowchart diagram
--ServiceModelType Includes API contract or HTTP sequence diagrams

๐Ÿ“ MkDocs Structure Example (mkdocs.yml)

site_name: MyService Docs
theme:
  name: material
nav:
  - Home: index.md
  - Architecture: architecture.md
  - Domain Model: domain-model.md
  - Messaging: messaging.md
  - Configuration: configuration.md
  - Observability: observability.md
  - Use Cases: use-cases.md
  - Diagrams:
      - Architecture: diagrams/architecture-structure.mmd
      - Sequence: diagrams/domain-sequence.mmd

โœ… Automatically rendered into a Material Design static site


๐Ÿ“Š Mermaid Diagram Support

  • Included via:

    • docs/diagrams/*.mmd
    • Mermaid plugin enabled in mkdocs.yml
    • Supports:

    • C4 diagrams

    • Flowcharts
    • Sequence diagrams
    • State machines

Example: Architecture Structure Diagram

graph TD
  UI[API Host / Bot Host / Job Host]
  UI --> App[Application Layer]
  App --> Domain[DomainModel]
  App --> Infra[Infrastructure Layer]
  Infra --> DB[(Database)]
  Infra --> Bus[(Message Bus)]
Hold "Alt" / "Option" to enable pan & zoom

Example: Domain Sequence

sequenceDiagram
  participant User
  participant Controller
  participant UseCase
  participant Repository

  User->>Controller: POST /orders
  Controller->>UseCase: Execute(CreateOrder)
  UseCase->>Repository: Save(Order)
  Repository-->>UseCase: OrderId
  UseCase-->>Controller: OrderCreated
Hold "Alt" / "Option" to enable pan & zoom

โœ… Can be rendered inline or embedded in pages


๐Ÿ“– DDD Support in Docs

Each template includes generated docs for:

Section Source
domain-model.md From EntityModel, ValueObjects, Aggregates
use-cases.md Extracted from DomainModel + ApplicationModel
messaging.md Event and command contracts
observability.md Trace, metric, log structure
configuration.md From Options/ + appsettings structure

๐Ÿง  Agent Compatibility

  • AI agents can:

    • Navigate the docs programmatically
    • Extract metadata for execution graphs
    • Render new diagrams dynamically
    • Insert AI-generated sections into Markdown
    • Summarize structure for planning flows

โœ… All documentation is AI-parsable and navigable โœ… Skills and planners can ingest Mermaid, Markdown, and YAML structure


๐Ÿงช Developer Usage

  • Run mkdocs serve to preview locally
  • Publish to:

    • GitHub Pages
    • Azure Static Web Apps
    • docs.connectsoft.dev (agent-published)

โœ… Works inside containerized dev environment


โœ… Summary

  • The template includes ready-to-use, styled, agent-compatible documentation
  • Powered by:

    • MkDocs
    • Material UI
    • Mermaid
    • Supports:

    • Clean Architecture

    • Use cases
    • Sequence flows
    • Deployment diagrams
    • Ideal for both developer onboarding and agent orchestration

๐Ÿ“ข Domain Events, Outbox, and Event Publication

The ConnectSoft Microservice Template provides first-class support for domain event propagation and outbox-based message publishing to ensure:

  • โœ… Event-Driven Architecture (EDA) consistency
  • ๐Ÿ”„ Reliable messaging without data loss
  • ๐Ÿงฑ Clean separation between domain and infrastructure
  • ๐Ÿง  Agent-traceable events across services

๐Ÿงฉ Domain events are raised in the domain layer, collected in the application layer, and dispatched in the infrastructure layer via configurable buses.


๐Ÿ” Domain Event Lifecycle

sequenceDiagram
  participant Domain as Aggregate
  participant Collector as IEventCollector
  participant App as UseCaseHandler
  participant Bus as EventPublisher

  Domain->>Collector: AddDomainEvent()
  Collector-->>App: CollectUnpublishedEvents()
  App->>Bus: Publish(events)
  Bus-->>Infra: Dispatch to bus or outbox
Hold "Alt" / "Option" to enable pan & zoom

๐Ÿ“ฆ Event Publication Projects

Project Description
DomainModel Defines IDomainEvent, domain events
ApplicationModel Collects uncommitted events during use case execution
InfrastructureModel Publishes events via bus, outbox, or webhook
MessagingModel Defines externalized integration events (pub/sub)

๐Ÿงฑ Domain Event Declaration

public record OrderPlacedEvent(OrderId Id, DateTime Timestamp) : IDomainEvent;

Raised inside aggregates:

AddDomainEvent(new OrderPlacedEvent(Id, DateTime.UtcNow));

โœ… Stored temporarily in memory via IEventCollector โœ… Published after successful unit of work completion


๐Ÿ”„ Outbox Pattern (Optional)

When enabled (e.g., via MassTransit or NServiceBus):

  • Domain events are persisted in an outbox table or collection
  • A background job or transactional bus middleware then dispatches them
  • Ensures no message loss on crashes or rollback

Benefits:

  • Atomic with DB write
  • Retry-safe
  • Message deduplication support
  • Works with SQL, Mongo, or Cosmos

๐Ÿ›  Bus Dispatchers

Bus Dispatcher
MassTransit IEventPublisher โ†’ Publish<T>() or Send<T>()
NServiceBus IMessageSession โ†’ Publish()
Dapr (optional) HTTP call to pub/sub binding
Webhook IWebhookDispatcher or custom client integration

๐Ÿ”Œ Integration Event Example

public record OrderConfirmedIntegrationEvent(string OrderId, string Email) : IIntegrationEvent;
  • Enriched with TenantId, CorrelationId, TraceId
  • Mapped from domain event via handler or converter

โœ… Enables internal โ†’ external message separation


๐Ÿ“Š Observability

Every published event is:

  • ๐Ÿ”Ž Logged (structured)
  • ๐Ÿ“ก Traced with OpenTelemetry span: event.publish.{eventName}
  • ๐Ÿงช Measured (e.g., events_published_total, event_latency_seconds)
  • ๐Ÿง  Tagged with:

    • event_type
    • tenant
    • trigger_source (e.g., usecase, job, actor)

๐Ÿงช Testing Strategy

Level Test Type
Domain Verify AddDomainEvent() in aggregate behavior tests
Application Assert that events are collected in IEventCollector
Infrastructure Test bus interaction via TestHarness or spy
BDD Assert OrderPlacedEvent is published on scenario success

๐Ÿง  AI Agent Support

Agents can:

  • Inspect DomainModel.yaml to identify events
  • Suggest new event listeners, projections, or pub/sub flows
  • Auto-generate integration event adapters
  • Record and trace events as part of semantic execution graph
  • Visualize system behavior from event graph

โœ… Fully compatible with planner reasoning โœ… Future roadmap: temporal event graph summarization


โœ… Summary

  • Domain events are:

    • Raised in aggregates
    • Collected in memory
    • Published after success
    • Outbox pattern is bus-agnostic and reliable
    • Metrics, traces, and logs support full observability
    • Used for:

    • EDA flows

    • Event sourcing
    • AI integration
    • External pub/sub systems

๐ŸŒ API Gateway and Edge Routing Integration

The ConnectSoft Microservice Template integrates seamlessly with API gateway patterns, providing a unified approach for:

  • ๐Ÿšช Service entrypoint routing
  • ๐Ÿ” Centralized authentication and authorization
  • ๐Ÿงญ Request transformation and enrichment
  • ๐Ÿ“Š Aggregated observability and telemetry
  • ๐ŸŽฏ Multi-tenant edge segmentation

๐Ÿ”„ Supports out-of-the-box compatibility with YARP, Azure API Management, NGINX Ingress, and custom reverse proxies.


๐Ÿ“ฆ Gateway Models Supported

Gateway Purpose
YARP (ASP.NET Core) Developer-friendly, pluggable reverse proxy
Azure API Management Enterprise-grade, secure API publication
NGINX / Traefik Kubernetes ingress controllers
Custom Gateways Optional ConnectSoft-built proxies or orchestrators

โš™๏ธ Template Parameters

Parameter Description
--ServiceModelType Required for exposed APIs (REST/gRPC/GraphQL)
--UseAuthentication Enables gateway-based auth passthrough
--UsePulumi Can provision API Management or Ingress
--HttpPort / --HttpsPort Maps container to edge gateway route
--FeatureFlags Enables edge feature routing by edition/tenant

๐Ÿงญ YARP (Reverse Proxy in .NET)

Sample YARP config:

{
  "ReverseProxy": {
    "Routes": {
      "orders": {
        "ClusterId": "orders",
        "Match": { "Path": "/orders/{**catch-all}" }
      }
    },
    "Clusters": {
      "orders": {
        "Destinations": {
          "orderApp": { "Address": "http://orders-service" }
        }
      }
    }
  }
}

โœ… Edge routing with optional tenant and path filtering โœ… Runs as dedicated ASP.NET Core app or within gateway-hosted containers


๐Ÿงฉ Azure API Management Integration

If --UsePulumi and --UseAuthentication:

  • Provisions:

    • API registration (OpenAPI import)
    • Product assignment
    • Subscription key enforcement
    • Supports:

    • OAuth2 bearer validation

    • Policy-based header transformation
    • Rate limiting and usage quotas

โœ… Integrates with ConnectSoft SaaS edition model for plan-based API tiers


๐Ÿ›ก๏ธ Gateway Security

Feature Supported
JWT passthrough โœ… via header propagation
Role-based blocking โœ… via route policies
Tenant segmentation โœ… via header/token claim mapping
IP filtering / CORS โœ… configured per edge
Rate limiting โœ… via API Management or YARP middleware

๐Ÿงช Route Testing & Edge Validation

Scenario Test Tool
Path routing Postman + YARP test profile
Auth passthrough JWT token with roles + tenant claim
gRPC proxying gRPC-Web with edge config
Swagger publication Import OpenAPI into API Management
Ingress traffic K8s + NGINX with /health/ready check

๐Ÿ“Š Observability from Gateway

  • Propagates X-Correlation-ID, X-Tenant-ID, traceparent
  • Logs edge telemetry via:

    • Azure Monitor
    • Serilog sink
    • YARP diagnostics
    • Metric endpoints exposed to:

    • Prometheus

    • API Management Analytics
    • Grafana dashboards

๐Ÿง  AI Agent Usage

Agents can:

  • Generate gateway route definitions from ServiceModel.yaml
  • Bind OpenAPI specs to edge entries
  • Detect misrouted or missing services via probing
  • Extend edge configuration for A/B testing, Canary deploys
  • Recommend security policies or JWT validation rules

โœ… AI-aware services can self-register at the gateway via planner hooks


โœ… Summary

  • ConnectSoft microservices integrate with standard API gateways
  • Supports:

    • YARP (reverse proxy)
    • Azure API Management
    • K8s ingress controllers
    • Enables:

    • Auth, rate limiting, tenant routing

    • Secure edge interfaces
    • AI-assisted deployment and API surfacing

๐Ÿงฑ Finalization, Use Cases, and Extensibility Paths

This final section consolidates the usage patterns, extensibility strategies, and real-world scenarios that the ConnectSoft Microservice Template supports.

It highlights how the template scales from a single service to a multi-agent, multi-tenant SaaS platform, including:

  • ๐Ÿง  Human and agent workflows
  • ๐Ÿ” Service evolution and modularity
  • ๐ŸŒ Industry-aligned use cases
  • ๐Ÿ”Œ Plugin and extension options
  • ๐Ÿ“ˆ Future-forward integration paths

๐Ÿงญ Usage Scenarios

Scenario Description
Domain-Oriented Microservice Aggregates, use cases, DDD events, REST/gRPC interface
Bot-Powered UX Bot Framework dialogs + Semantic Kernel skills
AI-Centric Service Semantic Kernel planner, skills, memory, prompt chaining
Workflow/Saga Coordinator Event-driven + actor-based + background jobs
Federated Identity Gateway OAuth2 integration with multi-tenant awareness
Composable SaaS Feature Embedded within larger SaaS platform with edition control

๐Ÿงฑ Extensibility Options

Area Extension Path
Persistence Add new database (e.g., DynamoDB, CockroachDB) via new PersistenceModel.* project
Messaging Integrate Kafka, Azure Event Grid, or Google Pub/Sub adapters
Actor Models Extend to Akka.NET, Proto.Actor, or Project Tye
Authentication Add multi-IDP federation, SCIM, SAML integration
AI Skills Auto-register from external plugins, graphQL schemas, OpenAPI endpoints
Gateway Add GraphQL Federation, YARP clustering, or API monetization tiers

โœ… All extensions follow a plugin-first, decoupled architecture


๐Ÿง  Agent-Driven Lifecycles

Agents can:

  • Use the template as code scaffolding source
  • Dynamically configure feature toggles, database types, message buses
  • Modify documentation, diagrams, and config in response to design changes
  • Generate infrastructure, integration tests, and observability policies
  • Trigger full microservice generation via MCP or planner

๐Ÿง  Every microservice is agent-compatible by design, including all trace, config, and interface metadata.


๐ŸŒ Real-World Use Cases Enabled

Domain Use Case
Insurance Claims engine, policy management, fraud detection
Healthcare Appointment service, EHR sync, lab report coordination
Education Student progress tracker, chatbot tutor, AI-based grading
E-commerce Order service, inventory actor, payment integration
Marketing Event router, CRM integration, Segment/Braze sync
Finance Portfolio simulator, billing engine, OpenAI financial insights

๐Ÿ“ Example Agent Execution Plan

agent: microservice-generator
input:
  AggregateRoot: Order
  PersistenceModel: NHibernate
  MessagingModel: MassTransit
  ActorModel: Orleans
  UseSemanticKernel: true
output:
  Folder: /src/OrderService
  DeploymentTarget: Kubernetes
  GitIntegration: Azure DevOps
  Observability: Prometheus + Grafana

โœ… Fully driven by planner โ†’ template โ†’ orchestrator โ†’ GitOps โ†’ deployment


๐Ÿงฉ Extensible Composition Units

Type Component
Aggregate EntityModel + DomainModel
API Mode ServiceModel.*
Job SchedulerModel.*
Actor ActorModel.*
Integration ExternalApis/Connector.cs
Test SpecFlow Feature + Step
Infra Pulumi Stack + Helm Chart

All components are optional, replaceable, and composable.


โœ… Summary

  • The ConnectSoft Microservice Template is a blueprint for scalable, intelligent, observable microservices
  • Designed for:

    • Enterprise SaaS
    • Agentic automation
    • Cloud-native operations
    • AI integration
    • Supports rapid generation, deep customization, and safe evolution
    • Works in harmony with ConnectSoft agents, DevOps pipelines, and real-world engineering teams