Chapter 1: Introduction to AI-Powered Applications in .NET 11
What You Will Learn
Explain what Microsoft.Extensions.AI, Semantic Kernel, and Microsoft Agent Framework each do in a .NET 11 application
Map the Contoso Support Copilot domain entities to their roles in a support workflow
Design interface boundaries that separate application logic from AI orchestration and agent coordination
Configure dependency injection for a multi-layered AI application, with one IChatClient shared by every layer
Position Microsoft Foundry (formerly Azure AI Foundry) as the model host beneath the abstraction layers
Prerequisites
No additional prerequisites beyond those listed in About This Book.
Concept Overview
Three libraries share the work in a .NET 11 AI application. Microsoft.Extensions.AI provides the abstractions: IChatClient for chat models and IEmbeddingGenerator for embedding models. Semantic Kernel adds prompt templates and plugins, named groups of functions such as C# methods, on the same IChatClient (Chapter 4). Microsoft Agent Framework, Semantic Kernel's successor, builds on Microsoft.Extensions.AI and adds agents and multi-agent workflows (Chapters 10 and 11). New features go to Agent Framework. This book therefore keeps Semantic Kernel behind one application interface, so replacing it later is a contained change.
A model reads and writes text as tokens, pieces of words about four characters long in English; providers count and bill the tokens in and out, and a request can cap the tokens out. Reasoning models, such as the GPT-5 series, write hidden reasoning tokens before they answer. Those count against the same cap and the bill. An embedding is a list of numbers that stands for a text's meaning, so similar texts get similar lists (Chapter 7). An agent is a model that can ask your code to run C# methods, called tools, until it can answer (Chapter 10).
The book builds Contoso Support Copilot, which helps support engineers triage tickets, search product knowledge, draft replies grounded in approved knowledge articles, summarize cases, and prepare escalations. A person approves every suggestion. Microsoft Foundry hosts the models: at the time of writing, a GPT-5-series chat model such as gpt-5.4-mini and an embedding model such as text-embedding-3-small. Foundry serves each model as a deployment, under a name you choose, and the code reads deployment names from configuration, so changing models never touches code.
One principle governs the design: domain services never depend directly on AI infrastructure. They depend on abstractions that hide model invocation, prompt templating, and agent coordination. When the layers blur, a unit test of a support workflow suddenly needs a model deployment, and an SDK upgrade reaches into business rules.
Domain code never references Semantic Kernel's Kernel or Agent Framework's AIAgent.
The application has four layers, from the support portal down to the model host (Figure 1.1):
Application services such as SupportCopilotService, in the Domain project, depend only on Contoso contracts: ISupportContext for tickets and articles, plus ISupportChatClient, IKernelOrchestrator, and IAgentCoordinator for model calls, prompt workflows, and agents.
The Infrastructure project implements them: InMemorySupportContext, SupportChatClient on Microsoft.Extensions.AI, SemanticKernelOrchestrator on Semantic Kernel, and AgentFrameworkCoordinator, whose model-calling agents use Agent Framework from Chapter 10.
Microsoft.Extensions.AI supplies the one IChatClient that the three AI implementations share.
Microsoft Foundry hosts the deployments that the IChatClient and the embedding generator call.
Figure 1.1. SupportCopilotService reaches the AI layers only through three contracts in the Domain project. Behind them, SupportChatClient uses the shared IChatClient now, and SemanticKernelOrchestrator (from Chapter 2) and AgentFrameworkCoordinator's agents (from Chapter 10) will use the same one. In this chapter OfflineChatClient answers in place of a model; from Chapter 2 on, Microsoft Foundry, Ollama or OpenAI can host the models.
Step-by-Step Implementation
The companion code's Chapter01 folder already holds every file this chapter describes, so read each step with its file open: open Chapter01/ContosoSupportCopilot.slnx in Visual Studio with File > Open > Project/Solution, or open the folder in VS Code with C# Dev Kit. Its projects are ContosoSupportCopilot.Domain for entities and contracts, ContosoSupportCopilot.Infrastructure for implementations, and ContosoSupportCopilot.Api for the host. Chapter 2 shows how to create them; from then on you can make each chapter's changes in your own solution or read along in the next ChapterNN folder. In a listing marked (excerpt), // ... marks omitted code, and the using directives and namespace line are left out; the complete file is in the chapter's companion-code folder.
First, Run the Offline Path in Visual Studio
Open Chapter01/ContosoSupportCopilot.slnx, set ContosoSupportCopilot.Api as the startup project and select Offline check, as About This Book shows. Build with Ctrl+Shift+B, then press Ctrl+F5. Expect the provider to be Offline, the model to be offline-sample and the final line to read Check passed. No model account is needed.
Now trace one request: ChapterCheck asks SupportCopilotService for a summary, that service calls ISupportChatClient, SupportChatClient adapts it to IChatClient, and OfflineChatClient supplies the sample answer. The interfaces below name those boundaries. You do not need to memorize every type before following that one path. Chapter 2 creates the solution; this chapter reads and runs its supplied foundation.
Step 1: Define the Core Domain Entities
Every AI workflow summarizes, classifies, or answers a SupportTicket. TicketMessage is one message of its thread, CustomerAccount the customer, and SupportCaseSummary an AI summary.
// File: ContosoSupportCopilot.Domain/Models/SupportTicket.cs
namespace ContosoSupportCopilot.Domain.Models;
public record SupportTicket
{
public Guid Id { get; init; }
public string Subject { get; init; } = string.Empty;
public string Description { get; init; } = string.Empty;
public string Status { get; init; } = "Open";
public string Priority { get; init; } = "Normal";
public string ProductArea { get; init; } = string.Empty;
public DateTime CreatedAt { get; init; }
public DateTime? ResolvedAt { get; init; }
public List<TicketMessage> Messages { get; init; } = new();
public CustomerAccount? Customer { get; init; }
}
public record TicketMessage
{
public Guid Id { get; init; }
public string Content { get; init; } = string.Empty;
public bool IsFromCustomer { get; init; }
public DateTime SentAt { get; init; }
}
public record CustomerAccount
{
public Guid Id { get; init; }
public string Name { get; init; } = string.Empty;
public string Tier { get; init; } = string.Empty;
}
public record SupportCaseSummary
{
public Guid TicketId { get; init; }
public string Summary { get; init; } = string.Empty;
public DateTime GeneratedAt { get; init; }
public int InputTokens { get; init; }
public int OutputTokens { get; init; }
}
Init-only properties make the records shallowly immutable. Nothing can be reassigned, but the Messages list can still change, so treat collections in records as read-only and copy them before concurrent work shares a record.
Step 2: Define the KnowledgeArticle and ArticleChunk Entities
KnowledgeArticle is approved documentation that the copilot searches and cites. ArticleChunk is a piece of an article with its embedding, which Chapter 7 searches.
// File: ContosoSupportCopilot.Domain/Models/KnowledgeArticle.cs
namespace ContosoSupportCopilot.Domain.Models;
public record KnowledgeArticle
{
public Guid Id { get; init; }
public string Title { get; init; } = string.Empty;
public string Content { get; init; } = string.Empty;
public string ProductArea { get; init; } = string.Empty;
public string[] Tags { get; init; } = Array.Empty<string>();
public DateTime LastUpdated { get; init; }
public bool IsPublished { get; init; }
public List<ArticleChunk> Chunks { get; init; } = new();
}
public record ArticleChunk
{
public Guid Id { get; init; }
public string Content { get; init; } = string.Empty;
public float[] Embedding { get; init; } = Array.Empty<float>();
public int ChunkIndex { get; init; }
}
Search skips unpublished articles, so IsPublished keeps unapproved content out of answers. From Chapter 7, the vector store keeps the chunks, and a search returns each article with its matching chunks in Chunks.
Step 3: Define the ISupportContext Interface
ISupportContext is the data access boundary. AI code never sees Entity Framework Core.
GetTicketMessagesAsync returns the thread that summarization needs. SearchKnowledgeBaseAsync can move to vector search later without a change to its signature or its callers.
Step 4: Define the ISupportChatClient Abstraction
The Domain project references no packages, so it declares its own contract, ISupportChatClient, which Step 8 implements over IChatClient. The Support prefix keeps its records from colliding with ChatResponse and ChatOptions in a file that imports both namespaces.
// File: ContosoSupportCopilot.Domain/Models/SupportChatModels.cs
namespace ContosoSupportCopilot.Domain.Models;
public record SupportChatResponse
{
public string Content { get; init; } = string.Empty;
public int InputTokens { get; init; }
public int OutputTokens { get; init; }
public string ModelId { get; init; } = string.Empty;
public string FinishReason { get; init; } = string.Empty;
}
public record SupportChatChunk
{
public string Content { get; init; } = string.Empty;
public bool IsComplete { get; init; }
public int InputTokens { get; init; }
public int OutputTokens { get; init; }
}
public record SupportChatOptions
{
public string? SystemPrompt { get; init; }
public int? MaxOutputTokens { get; init; }
public float? Temperature { get; init; }
}
SupportChatResponse carries the token counts, the model ID, and the finish reason, which says why the answer ended: stop for a natural end, length at the token limit. Without per-call token counts, a monthly model bill cannot tell you which feature caused the cost. In SupportChatOptions, Temperature and MaxOutputTokens default to null. Leave Temperature unset, because most reasoning models, the GPT-5 series included, reject a non-default temperature, and let each caller size MaxOutputTokens for its own answer.
Token counts belong in the contract from the first day.
Step 5: Define the IKernelOrchestrator Interface
Prompt orchestration gets its own contract, so application code never depends on Semantic Kernel types.
ExecuteStructuredPromptAsync returns a typed object deserialized from the model's JSON answer; Chapter 5 replaces this method with a pipeline that validates the answer. The two plugin methods register and call plugin functions by name.
Step 6: Define the IAgentCoordinator Interface
Agent execution and handoff get a thin Contoso wrapper, not framework types. From Chapter 10, agents that call a model delegate to an Agent Framework ChatClientAgent behind it. First, the records that agents exchange:
// File: ContosoSupportCopilot.Domain/Models/AgentModels.cs
namespace ContosoSupportCopilot.Domain.Models;
public record AgentContext
{
public Guid ConversationId { get; init; }
public SupportTicket? CurrentTicket { get; init; }
public string Intent { get; init; } = string.Empty;
public Dictionary<string, object> Metadata { get; init; } = new();
}
public record AgentResult
{
public string Response { get; init; } = string.Empty;
public bool RequiresHandoff { get; init; }
public string? NextAgent { get; init; }
public Dictionary<string, object> Artifacts { get; init; } = new();
}
AgentContext carries the ticket, and RequiresHandoff lets one agent delegate to another. Metadata and Artifacts are plain dictionaries, unsafe to change from two threads at once, so give concurrent agents their own context: context with { Metadata = new(context.Metadata) }.
Step 7: Implement an In-Memory Support Context
Until Chapter 2 adds a database, InMemorySupportContext serves the contract from the sample tickets and articles of the companion code's SampleData class, in the same folder. The methods left out filter the same two lists.
Each scope gets its own copy of the data, which suits a stand-in and needs no locking.
Step 8: Implement the SupportChatClient Adapter
SupportChatClient delegates to whatever IChatClient is registered and contains no provider code.
// File: ContosoSupportCopilot.Infrastructure/AI/SupportChatClient.cs (excerpt)
public class SupportChatClient : ISupportChatClient
{
private readonly IChatClient _chatClient;
public SupportChatClient(IChatClient chatClient)
{
_chatClient = chatClient;
}
public async Task<SupportChatResponse> CompleteAsync(string prompt, SupportChatOptions? options = null, CancellationToken cancellationToken = default)
{
ChatResponse response = await _chatClient.GetResponseAsync(prompt, ToChatOptions(options), cancellationToken);
return new SupportChatResponse
{
Content = response.Text,
InputTokens = (int)(response.Usage?.InputTokenCount ?? 0),
OutputTokens = (int)(response.Usage?.OutputTokenCount ?? 0),
ModelId = response.ModelId ?? string.Empty,
FinishReason = response.FinishReason?.Value ?? string.Empty
};
}
public async IAsyncEnumerable<SupportChatChunk> CompleteStreamingAsync(
string prompt,
SupportChatOptions? options = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
var updates = new List<ChatResponseUpdate>();
await foreach (var update in _chatClient.GetStreamingResponseAsync(prompt, ToChatOptions(options), cancellationToken))
{
updates.Add(update);
if (update.Text.Length > 0)
{
yield return new SupportChatChunk { Content = update.Text };
}
}
// Providers report usage in the final updates; ToChatResponse collects it.
UsageDetails? usage = updates.ToChatResponse().Usage;
yield return new SupportChatChunk
{
IsComplete = true,
InputTokens = (int)(usage?.InputTokenCount ?? 0),
OutputTokens = (int)(usage?.OutputTokenCount ?? 0)
};
}
private static ChatOptions? ToChatOptions(SupportChatOptions? options) => options is null
? null
: new ChatOptions
{
Instructions = options.SystemPrompt,
MaxOutputTokens = options.MaxOutputTokens,
Temperature = options.Temperature
};
}
CompleteAsync copies the text, token counts, model, and finish reason into the domain record. CompleteStreamingAsync forwards each text update and keeps them all, so the closing chunk, marked IsComplete, carries accurate counts for a streamed reply too.
In ToChatOptions, the system prompt becomes ChatOptions.Instructions and MaxOutputTokens becomes the output limit, which the OpenAI SDK sends as max_completion_tokens. On a reasoning model that limit also covers hidden reasoning tokens, so leave headroom.
Step 9: Implement the SemanticKernelOrchestrator Class
The orchestrator is a stub for now. Each method throws a NotImplementedException that names Chapter 2, which implements it with Semantic Kernel on the same IChatClient.
// File: ContosoSupportCopilot.Infrastructure/AI/SemanticKernelOrchestrator.cs (excerpt)
public class SemanticKernelOrchestrator : IKernelOrchestrator
{
public Task<string> ExecutePromptAsync(string promptTemplate, Dictionary<string, object> variables, CancellationToken cancellationToken = default)
=> throw new NotImplementedException("Chapter 2 implements prompt execution with Semantic Kernel.");
// ...
public Task<string> ExecutePluginFunctionAsync(string pluginName, string functionName, Dictionary<string, object> parameters, CancellationToken cancellationToken = default)
=> throw new NotImplementedException("Chapter 2 implements plugin functions with Semantic Kernel.");
}
Step 10: Implement the AgentFrameworkCoordinator and TriageAgent Classes
AgentFrameworkCoordinator keeps a registry of named agents and resolves a name when ExecuteAgentAsync runs. TriageAgent is the first IAgent, a stub until Chapter 10.
// File: ContosoSupportCopilot.Infrastructure/Agents/AgentFrameworkCoordinator.cs (excerpt)
public class AgentFrameworkCoordinator : IAgentCoordinator
{
// One instance serves every request, so a registration can run while other requests look agents up.
private readonly ConcurrentDictionary<string, IAgent> _agents = new();
public Task RegisterAgentAsync(string agentName, IAgent agent, CancellationToken cancellationToken = default)
{
_agents[agentName] = agent;
return Task.CompletedTask;
}
public Task<AgentResult> ExecuteAgentAsync(string agentName, AgentContext context, CancellationToken cancellationToken = default)
{
if (!_agents.TryGetValue(agentName, out var agent))
throw new ArgumentException($"Agent {agentName} not registered", nameof(agentName));
return agent.ExecuteAsync(context, cancellationToken);
}
public Task HandoffAsync(string fromAgent, string toAgent, AgentContext context, CancellationToken cancellationToken = default)
=> throw new NotImplementedException("Chapter 2 implements agent handoff.");
}
// File: ContosoSupportCopilot.Infrastructure/Agents/TriageAgent.cs (excerpt)
public class TriageAgent : IAgent
{
public string Name { get; }
public TriageAgent(string name) => Name = name;
public Task<AgentResult> ExecuteAsync(AgentContext context, CancellationToken cancellationToken = default)
=> throw new NotImplementedException("Chapter 10 implements the triage agent.");
}
The registry lives in the coordinator, so the coordinator must be a singleton.
Step 11: Implement the SupportCopilotService
SupportCopilotService composes the layers and is the API the support portal consumes; Figure 1.1 shows it above the three contracts. It depends only on domain contracts, so it lives in the Domain project, in the ContosoSupportCopilot.Application.Services namespace; there is no Application project, and the namespace marks the application layer:
// File: ContosoSupportCopilot.Domain/Application/SupportCopilotService.cs (excerpt)
public class SupportCopilotService
{
private readonly ISupportContext _supportContext;
private readonly ISupportChatClient _chatClient;
private readonly IKernelOrchestrator _kernelOrchestrator;
private readonly IAgentCoordinator _agentCoordinator;
// ...
public async Task<string> DraftReplyAsync(Guid ticketId, CancellationToken cancellationToken = default)
{
// ...
return await _kernelOrchestrator.ExecutePromptAsync(
"Draft a professional support response for the following ticket about {{$productArea}}.\n\n" +
"Subject: {{$ticketSubject}}\nDescription: {{$ticketDescription}}\n\n" +
"Consider these knowledge articles: {{$relevantArticles}}",
context,
cancellationToken);
}
// ...
public async Task<SupportCaseSummary> SummarizeTicketAsync(Guid ticketId, CancellationToken cancellationToken = default)
{
var ticket = await _supportContext.GetTicketAsync(ticketId, cancellationToken);
if (ticket is null)
{
throw new ArgumentException($"Ticket {ticketId} not found", nameof(ticketId));
}
var messages = await _supportContext.GetTicketMessagesAsync(ticketId, cancellationToken);
var messageHistory = string.Join("\n", messages.Select(m => $"{(m.IsFromCustomer ? "Customer" : "Agent")}: {m.Content}"));
var prompt = $"Summarize the following support ticket concisely. Identify the key issue, current status, and recommended next steps.\n\nSubject: {ticket.Subject}\nDescription: {ticket.Description}\nStatus: {ticket.Status}\n\nMessage History:\n{messageHistory}";
var response = await _chatClient.CompleteAsync(prompt, new SupportChatOptions { MaxOutputTokens = 2000 }, cancellationToken);
return new SupportCaseSummary
{
TicketId = ticketId,
Summary = response.Content,
GeneratedAt = DateTime.UtcNow,
InputTokens = response.InputTokens,
OutputTokens = response.OutputTokens
};
}
// ...
public async Task<AgentResult> TriageTicketAsync(Guid ticketId, CancellationToken cancellationToken = default)
{
// ...
return await _agentCoordinator.ExecuteAgentAsync("TriageAgent", context, cancellationToken);
}
}
Each method uses one AI contract. DraftReplyAsync searches the knowledge base, puts the ticket's subject, description, and product area, with each article's title and first 200 characters, into the context dictionary, and runs a prompt template through IKernelOrchestrator. SummarizeTicketAsync calls ISupportChatClient with only MaxOutputTokens set and returns the token counts in a SupportCaseSummary. TriageTicketAsync builds an AgentContext and runs the triage agent through IAgentCoordinator. Only SummarizeTicketAsync returns an answer in this chapter; the other two reach stubs that throw NotImplementedException until Chapter 2 (the orchestrator) and Chapter 10 (the triage agent).
{{$productArea}} is a Semantic Kernel placeholder, filled from the dictionary entry with the same key; Chapter 4 explains templates.
The summary prompt mixes instructions and customer text in one string, which invites prompt injection: a message that says "ignore the instructions above" reads like part of them. Chapter 3 separates the two with message roles, delimiters, and escaping; Chapter 6 adds a summary that separates them, and Chapter 10 rewrites this method.
Step 12: Configure Dependency Injection
Program.cs wires the layers together. Its chat client, OfflineChatClient from the companion code's ContosoSupportCopilot.Infrastructure/AI/Offline folder, answers locally with deterministic sample text and estimated token counts. Apart from its constructor and two constants, it exposes only the IChatClient members and Dispose:
// File: ContosoSupportCopilot.Infrastructure/AI/Offline/OfflineChatClient.cs (excerpt)
public sealed class OfflineChatClient : IChatClient
{
public const string ProviderName = "Offline";
public const string ModelName = "offline-sample";
// ...
public void Dispose()
{
}
}
Program.cs, shown whole in the Full Example, registers it with AddChatClient as the application's one IChatClient, a singleton, because chat clients are thread-safe and reuse their connections. The triage agent is registered by name once, after the host is built.
To run the chapter's check in Visual Studio, make ContosoSupportCopilot.Api the startup project (right-click it in Solution Explorer and choose Set as Startup Project), select Offline check beside the green Start button and press Ctrl+F5. Choose http to start the API itself; it listens on http://localhost:5101 but maps no endpoints until Chapter 2 adds health checks, so every request returns 404 Not Found. From a terminal in the Chapter01 folder:
dotnet run --project ContosoSupportCopilot.Api -- --check
ChapterCheck.RunAsync, in the Api project's ChapterCheck.cs, runs the summary path once, streams a short reply, prints the token counts, and exits. Its first line names the provider and model (Offline and offline-sample here), its answers are labeled offline sample text, which shows the application's flow, not a model's quality, and its last line reads Check passed. Every chapter's check ends that way, or with a line that names what failed.
Follow the Adapter with the Visual Studio Debugger
Open Infrastructure/AI/SupportChatClient.cs and set a breakpoint on the line that awaits _chatClient.GetResponseAsync. Keep Offline check selected and press F5. Locals shows the prompt and options; _chatClient is the offline implementation behind the interface. The breakpoint stops before this call completes.
Press F10 to step over the call, then inspect response.Text, response.ModelId and response.Usage in Locals. They describe the deterministic offline answer. Press F10 to execute the return expression; Visual Studio stops at the method's closing brace. Press F10 once more to return to SupportCopilotService, then use Debug > Windows > Call Stack to follow your application frames. This is the adapter boundary: provider-library types become the domain's SupportChatResponse. Remove the breakpoint and continue with F5. Use synthetic sample tickets while inspecting prompts in a debugger.
Full Example
Program.cs is where the four layers meet. This is the file as it stands at the end of the chapter, in the companion code's Chapter01 folder:
// File: ContosoSupportCopilot.Api/Program.cs
using ContosoSupportCopilot.Api;
using ContosoSupportCopilot.Application.Services;
using ContosoSupportCopilot.Domain.Services;
using ContosoSupportCopilot.Infrastructure.Agents;
using ContosoSupportCopilot.Infrastructure.AI;
using ContosoSupportCopilot.Infrastructure.AI.Offline;
using ContosoSupportCopilot.Infrastructure.Data;
var builder = WebApplication.CreateBuilder(args);
// Domain and application services
builder.Services.AddScoped<ISupportContext, InMemorySupportContext>();
builder.Services.AddScoped<SupportCopilotService>();
// Microsoft.Extensions.AI layer: one IChatClient for the whole application.
// The offline client answers locally; Chapter 2 adds the provider switch.
builder.Services.AddChatClient(new OfflineChatClient());
builder.Services.AddSingleton<ISupportChatClient, SupportChatClient>();
// Semantic Kernel orchestration layer
builder.Services.AddSingleton<IKernelOrchestrator, SemanticKernelOrchestrator>();
// Agent coordination layer
builder.Services.AddSingleton<IAgentCoordinator, AgentFrameworkCoordinator>();
builder.Services.AddSingleton(new TriageAgent("TriageAgent"));
var app = builder.Build();
// Register agents with the coordinator by name
var coordinator = app.Services.GetRequiredService<IAgentCoordinator>();
await coordinator.RegisterAgentAsync("TriageAgent", app.Services.GetRequiredService<TriageAgent>());
if (args.Contains("--check"))
{
return await ChapterCheck.RunAsync(app.Services);
}
app.Run();
return 0;
The other files of the checkpoint, all in the Chapter01 folder:
ContosoSupportCopilot.Domain/Models: SupportTicket.cs, KnowledgeArticle.cs, SupportChatModels.cs, and AgentModels.cs, the records (Steps 1, 2, 4, and 6).
ContosoSupportCopilot.Domain/Services: ISupportContext.cs, ISupportChatClient.cs, IKernelOrchestrator.cs, and IAgentCoordinator.cs, the contracts (Steps 3 to 6).
ContosoSupportCopilot.Domain/Application/SupportCopilotService.cs: the application service (Step 11).
ContosoSupportCopilot.Infrastructure/Data: SampleData.cs and InMemorySupportContext.cs, the sample data and its context (Step 7).
ContosoSupportCopilot.Infrastructure/AI: SupportChatClient.cs, the adapter (Step 8), and SemanticKernelOrchestrator.cs, the stub (Step 9).
ContosoSupportCopilot.Infrastructure/Agents: AgentFrameworkCoordinator.cs and TriageAgent.cs, the registry and the stub agent (Step 10).
ContosoSupportCopilot.Infrastructure/AI/Offline: OfflineChatClient.cs and its helpers OfflineChatRequest.cs, OfflineResponder.cs, OfflineSupportClassifier.cs, and OfflineJson.cs, which build the sample answers (Step 12).
ContosoSupportCopilot.Api: ChapterCheck.cs, the --check path (Step 12), with appsettings.json and Properties/launchSettings.json for logging and the launch profile.
ContosoSupportCopilot.slnx and the three .csproj files: the solution, the net11.0 target, and Microsoft.Extensions.AI 10.11.0.
The Domain project has no package references. Application code reaches the model only through the three AI contracts, whose implementations work with any IChatClient, so the provider can change without touching SupportCopilotService.
Common Mistakes
Coupling domain logic to Semantic Kernel or Agent Framework types. A domain service that references Kernel or AIAgent resists testing and cannot swap implementations. Depend on this chapter's contracts instead.
Using the chat abstraction for orchestration.ISupportChatClient serves single request-response calls. Put multi-step prompt chains behind IKernelOrchestrator and multi-agent work behind IAgentCoordinator.
Registering the agent coordinator as a scoped service. Program.cs registers the agents on a coordinator resolved from the root provider. With a scoped coordinator, that call fails in Development, where scope validation rejects it; elsewhere it fills a root-scoped instance that no request uses, so each request's coordinator has an empty registry and agent lookups fail. Register stateful registries as singletons, and keep per-request state out of them.
Implementing agents before basic chat works. Agents call the model through the same IChatClient as the chat and orchestration layers. Built first, each agent invents its own way to call the model, and the contracts take the shape of whichever agent came first. Build the chat and orchestration layers first.
Leaving token usage out of the abstraction. Adding InputTokens and OutputTokens to SupportChatResponse later changes every implementation. Put them in from the start.
Doing expensive work in service constructors. The container runs a singleton's constructor on first use and a scoped service's constructor in every request. Loading models or opening Azure connections there delays the first request or every one, and a constructor that throws fails every request that resolves it. Keep constructors to assignments, and create clients once in a factory, as Chapter 2 does.
Performance and Production Considerations
Interface dispatch costs nothing measurable next to the network latency of a Microsoft Foundry call.
Test against the contracts. A mock ISupportChatClient with canned responses makes SupportCopilotService tests run in milliseconds without network calls, and a mock ISupportContext removes the database. A test double for IChatClient takes a few lines, because the interface has three members plus Dispose; OfflineChatClient is larger only because it imitates JSON output and streaming.
Streams are pull-based. Consume CompleteStreamingAsync with await foreach and pass a cancellation token, so a user who leaves the page stops the request instead of buffering an answer nobody reads.
Set latency budgets now. DraftReplyAsync composes a knowledge search with a model call; put the timeouts and circuit breakers (Chapter 4) such compositions need in the interface implementations, not in the application service, so every consumer gets the same resilience.
Summary
Contoso Support Copilot now has its foundation: domain records for tickets, messages, accounts, summaries, articles, and chunks, and three AI contracts, ISupportChatClient over Microsoft.Extensions.AI, IKernelOrchestrator over Semantic Kernel, and IAgentCoordinator over Microsoft Agent Framework. SupportCopilotService composes them without knowing any implementation, so it stays testable while the infrastructure changes. Program.cs wires every layer around one shared IChatClient, which Microsoft Foundry can serve from Chapter 2 on.
Key Terms
Microsoft.Extensions.AI: The shared .NET abstraction layer for model access: IChatClient, IEmbeddingGenerator<TInput, TEmbedding>, structured output helpers, and middleware.
IChatClient: The Microsoft.Extensions.AI interface for chat models, which SupportChatClient adapts to ISupportChatClient.
Semantic Kernel: A library for prompt templates and plugins that runs on the shared IChatClient; new features go to its successor, Agent Framework.
Microsoft Agent Framework: Semantic Kernel's successor, built on Microsoft.Extensions.AI, for agents, tools, sessions, handoffs, and multi-agent workflows.
IAgentCoordinator: A Contoso interface for agent coordination that keeps Agent Framework out of application code.
AgentContext: A Contoso record with the conversation, ticket, and metadata passed between agents.
Microsoft Foundry: Microsoft's platform for hosting AI models (formerly Azure AI Foundry), with the chat and embedding deployments the application calls.
Domain Entity: A core business object, such as SupportTicket, with no AI infrastructure dependencies.
Abstraction Layer: An interface boundary that isolates application logic from infrastructure, so implementations can be tested and replaced.
Token: A piece of text, about four characters of English, that a model reads or writes; the input and output token counts of each call are the basis of cost tracking.
Embedding: A list of numbers that stands for a text's meaning, so similar texts get similar lists; Chapter 7 searches knowledge articles by them.
Agent: A model that can ask your code to run C# methods, called tools, until it can answer; Chapter 10 builds agents on Agent Framework.
Mini Quiz
1. A ticket needs intent extraction, a knowledge base search, and a grounded reply draft. Which component orchestrates these steps while keeping the domain logic testable?
A. SupportChatClient, sending one model request for each step in turn
B. SupportCopilotService, through ISupportContext and IKernelOrchestrator
C. TriageAgent, running the whole workflow inside the Infrastructure project
D. InMemorySupportContext, because it already holds the ticket and the articles
2. Examine this domain service method:
public async Task<string> AnalyzeTicketAsync(Guid ticketId, CancellationToken cancellationToken)
{
var ticket = await _supportContext.GetTicketAsync(ticketId, cancellationToken)
?? throw new ArgumentException($"Ticket {ticketId} not found", nameof(ticketId));
var promptVariables = new Dictionary<string, object>
{
["subject"] = ticket.Subject,
["priority"] = ticket.Priority,
["description"] = ticket.Description
};
return await _kernelOrchestrator.ExecutePromptAsync(
"Analyze this {{$priority}} ticket.\nSubject: {{$subject}}\n{{$description}}",
promptVariables,
cancellationToken);
}
What does it show about this chapter's layering?
A. It reads the ticket through the orchestration layer, mixing data access and orchestration
B. It should take a Kernel, because only Semantic Kernel understands {{$priority}}
C. It ties the service to Microsoft Foundry, because an orchestrator calls only one provider
D. It depends only on the ISupportContext and IKernelOrchestrator contracts
3. Why does SupportCopilotService call ISupportChatClient instead of calling IChatClient directly?
A. The Domain project references no packages, so the service and its tests need no AI library
B. IChatClient cannot stream, so the service would lose the streaming method that ISupportChatClient offers
C. IChatClient is registered as a scoped service, and a domain service must not depend on scoped services
D. Semantic Kernel owns the registered IChatClient, so only IKernelOrchestrator is allowed to call it
4. Why does SupportCopilotService depend on the ISupportContext and IKernelOrchestrator interfaces rather than on concrete implementations?
A. So the service can be a singleton while its dependencies stay scoped
B. So the service can hold a Kernel and an AIAgent without referencing their packages
C. So tests and new providers can replace the implementations without changing the service
D. So each request gets a new orchestrator and coordinator, whatever lifetime the container uses
5. SummarizeTicketAsync asks for a concise summary but sets MaxOutputTokens to 2000. Why leave that much room?
A. The offline client ignores the limit, so the value matters only in tests
B. A reasoning model's hidden reasoning tokens count against the same limit as the answer
C. Providers bill every call for the full limit, so a high limit costs nothing extra
D. ISupportChatClient rejects limits below 2000 for streamed replies
6. What does SupportChatResponse carry next to the content, for observability and cost tracking?
A. The input and output token counts, the model ID, and the finish reason
B. The request ID, the latency in milliseconds, and the HTTP status code
C. The prompt text, the system prompt, and the temperature the call used
D. The deployment name, the API version, and the region that served it
Answers are provided in the Answer Key at the end of the book.
Activity
Add escalation drafting, which hands a ticket to engineering with a summary, reproduction steps, and the business impact in one record. The companion code's Chapter01/Activity folder contains a finished solution. SemanticKernelOrchestrator still throws in this chapter, so the tests in the last two steps, with a mocked orchestrator, are where you see DraftEscalationAsync work.
Create a record named EscalationDraft in ContosoSupportCopilot.Domain/Models with TicketId, EngineeringSummary, ReproductionSteps, and BusinessImpact.
Add Task SaveEscalationDraftAsync(EscalationDraft draft, CancellationToken cancellationToken = default) to ISupportContext, and implement it in InMemorySupportContext.
Add DraftEscalationAsync(Guid ticketId, CancellationToken cancellationToken) to SupportCopilotService: retrieve the ticket with _supportContext, build a prompt template that asks for an escalation analysis, and call _kernelOrchestrator.ExecutePromptAsync with the ticket's Subject, Description, Priority, and ProductArea as prompt variables named subject, description, priority, and productArea.
Build an EscalationDraft from the analysis (the analysis as EngineeringSummary, the ticket description as ReproductionSteps, and the priority and product area as BusinessImpact), save it with SaveEscalationDraftAsync, and return it.
If you have more time, add an xUnit Test Project named ContosoSupportCopilot.Tests (in Solution Explorer, right-click the solution and choose Add > New Project), reference ContosoSupportCopilot.Domain (right-click the test project in Solution Explorer and choose Add > Project Reference), and use Manage NuGet Packages to set the companion code's versions, which differ from the template's: xunit 2.9.3, xunit.runner.visualstudio 4.0.1, Microsoft.NET.Test.Sdk 18.11.0, and Moq 4.21.0. The CLI equivalents are dotnet new xunit, dotnet sln add, dotnet add reference, and dotnet add package.
Then write xUnit tests with Moq that mock ISupportContext to return a known test ticket and IKernelOrchestrator to return a fixed analysis, and verify that DraftEscalationAsync passes the expected prompt variables to the orchestrator and saves the draft. Run them from Test Explorer in Visual Studio, or with dotnet test. Chapter 6, Step 18, shows xUnit and Moq in full, and the Chapter01/Activity folder has working tests.
This second edition teaches AI integration from the application side. It assumes C# classes, interfaces, async methods, and dependency injection in ASP.NET Core, but no machine-learning experience.
Develop Contoso Support Copilot in one solution. Add ticket summaries, drafted replies, knowledge-base answers with citations, and small cooperating agents. Visual Studio 2026 is the main Windows path, with VS Code as an alternative.
What you will learn
Connect model providers through Microsoft.Extensions.AI.
Work with prompts, streaming, structured output, and conversation state.
Add embeddings, retrieval, and citations.
Coordinate bounded agent workflows and evaluate their behavior.
Track cost and reliability, and prepare the application for operation.
12 chapters include guided work, full examples, common mistakes, short quizzes with answers, and activities. Companion code is linked inside the book.
Release DateNovember 10, 2026
GenreSoftware & AI Development
ISBN979-8-90377-093-9
Read and listen on the go with the unQbd app.Get the app