Tutorials ASP.NET Core with Agentic AI Tutorial
AI Dependency Injection — Complete Guide
AI Dependency Injection — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of ASP.NET Core with Agentic AI Tutorial on Toolliyo Academy.
On this page
ASP.NET Core with Agentic AI Tutorial · Lesson 15 of 100
AI Dependency Injection
AI basics → Agents
AI basics · 1 — Setup · ~6 min · Module 2: ASP.NET Core AI Fundamentals
What is this?
Dependency injection registers IChatClient, Kernel, vector stores, and agents in the service container with correct lifetimes. AgentNest treats AI components like any other service — scoped for request work, singleton for clients.
Why should you care?
Testability and swapping OpenAI for Azure OpenAI per environment depend on constructor injection, not static SDK calls.
See it live — copy this example
Paste into an ASP.NET Core 8+ / AgentNest project, then run with dotnet run (set your API keys in user-secrets).
// AgentNest.Api/DependencyInjection/AiServiceCollectionExtensions.cs
public static class AiServiceCollectionExtensions
{
public static IServiceCollection AddAgentNestAi(this IServiceCollection services, IConfiguration config)
{
services.AddSingleton<IChatClient>(sp =>
sp.GetRequiredService<IChatClient>()); // registered by AddOpenAIChatClient
services.AddScoped<ICrmCopilotAgent, CrmCopilotAgent>();
services.AddScoped<IHospitalTriageAgent, HospitalTriageAgent>();
return services;
}
}
// Program.cs: builder.Services.AddAgentNestAi(builder.Configuration);
What happened?
- AddAgentNestAi groups AI registrations.
- Scoped agents get per-request isolation; chat clients stay singletons wrapping HTTP connections.
Practice next
- Create AiServiceCollectionExtensions in AgentNest.Api.
- Register agents as scoped; avoid transient Kernel builds.
- Replace IChatClient with a fake in unit tests via WebApplicationFactory.
- Add keyed services for OpenAI vs Azure per tenant feature flag.
- Register IEmbeddingGenerator alongside IChatClient.
Remember
Group AI DI in extension methods for AgentNest modules. Match lifetimes: singleton clients, scoped agents. Inject interfaces so tests swap fakes easily.
Swap model provider in CI
Pipeline tests must not call real OpenAI on every PR.
Outcome: DI replaces IChatClient with TestChatClient in WebApplicationFactory fixtures.
Interview prep for this lesson
Practice these questions aloud after reading—each links to a full structured answer.
Sign in to ask a question or upvote helpful answers.
No questions yet — be the first to ask!