.NET: AddAIAgent - Rename or add overload
Author: luisquintanillaCreated Sep 5, 2025Updated Sep 18, 2026
Labels.NETagents
AddAIAgent extension methods in the Hosting package implicitly register an AIAgent as a KeyedSingleton
When resolving the agent using DI, it's not obvious you need to use FromKeyedServices to get the agent. Using FromServices throws.
i.e.
Works
app.MapGet("/chat", async ([FromKeyedServices("user-agent")] AIAgent agent, string question) =>
{
AgentRunResponse agentResponse = await agent.RunAsync(question);
return Results.Ok(agentResponse.Text);
});Error
app.MapGet("/chat", async ([FromServices] AIAgent agent, string question) =>
{
AgentRunResponse agentResponse = await agent.RunAsync(question);
return Results.Ok(agentResponse.Text);
});Suggestions:
- Rename existing
AddAIAgenttoAddKeyedAIAgent - Add overloads for both
AddAIAgentandAddKeyedAIAgent
I'd be in favor of option 2.
Source: microsoft/agent-framework