Most teams' first LLM integration looks the same: a vendor SDK newed up inside a controller, an API key read from configuration, and a raw string passed back to the client. It works in the demo. Six months later you want to switch models, add caching, log token usage or write a unit test, and the SDK is tangled through your application layer.
Why an Abstraction Matters Here
Microsoft.Extensions.AI solves this the same way ILogger solved logging. The Microsoft.Extensions.AI.Abstractions package defines IChatClient and IEmbeddingGenerator; provider packages implement them; and the Microsoft.Extensions.AI package adds a middleware pipeline for function invocation, caching, logging and OpenTelemetry. Your application code depends on one interface, and the provider becomes a composition-root decision.
Wiring It Into Dependency Injection
Reference Microsoft.Extensions.AI plus a provider adapter, for example Microsoft.Extensions.AI.OpenAI. Then register the client once in Program.cs and build the pipeline there:
using Microsoft.Extensions.AI;
using OpenAI;
var builder = WebApplication.CreateBuilder(args);
IChatClient inner = new OpenAIClient(builder.Configuration["AI:ApiKey"])
.GetChatClient(builder.Configuration["AI:Model"])
.AsIChatClient();
builder.Services.AddDistributedMemoryCache();
builder.Services.AddChatClient(inner)
.UseDistributedCache()
.UseFunctionInvocation()
.UseOpenTelemetry()
.UseLogging();
Every service now takes IChatClient through its constructor. Swapping to Azure OpenAI or a local Ollama model during development changes only these lines. In tests, you register a fake IChatClient that returns canned responses, so your application logic is tested without network calls or token spend.
Typed Outputs Instead of String Parsing
Parsing free-form model text with regular expressions is where reliability goes to die. The GetResponseAsync<T> extension asks the model for JSON matching a .NET type and deserialises it for you:
public enum Priority { Low, Medium, High, Critical }
public record TicketTriage(string Category, Priority Priority, string Summary);
public sealed class TriageService(IChatClient chat)
{
public async Task<TicketTriage?> TriageAsync(string ticketText, CancellationToken ct)
{
var response = await chat.GetResponseAsync<TicketTriage>(
$"Classify this support ticket:\n{ticketText}",
cancellationToken: ct);
return response.TryGetResult(out var result) ? result : null;
}
}
By default a JSON schema is sent in the response format, which works well on models that support native structured output. If your model does not, pass useJsonSchemaResponseFormat: false and the schema is described in the prompt instead.
Tool Calling Without the Plumbing
Because the pipeline includes UseFunctionInvocation(), you can expose ordinary C# methods as tools. The middleware handles the request/response loop with the model:
using System.ComponentModel;
public sealed class OrderTools(IOrderRepository orders)
{
[Description("Gets the current status of an order by its number.")]
public Task<string> GetOrderStatusAsync(string orderNumber) =>
orders.GetStatusAsync(orderNumber);
}
var tools = new OrderTools(orderRepository);
var options = new ChatOptions
{
Tools = [AIFunctionFactory.Create(tools.GetOrderStatusAsync)]
};
var answer = await chat.GetResponseAsync("Where is order 10452?", options);
Keep tools narrow and read-only by default. A tool is an API endpoint that a non-deterministic caller can invoke with arguments you did not write, so validate inputs and authorise them exactly as you would for a public endpoint.
Pitfalls I See in Code Reviews
Treating model output as trusted
A typed result is still model output. Validate enum ranges, string lengths and IDs before you write anything to SQL Server or call another system. Never pass model-generated text straight into dynamic SQL.
Ignoring cancellation and timeouts
LLM calls are slow compared with a database round trip. Always flow the request's CancellationToken, and set an explicit timeout so a stalled provider does not tie up your request threads.
Logging prompts carelessly
OpenTelemetry and logging middleware are invaluable, but sensitive-data capture is opt-in for a reason. Leave it off in production unless you have a clear policy for personal data in prompts and responses.
Caching the wrong things
Response caching is effective for deterministic, repeated prompts such as classification of identical inputs. It is the wrong tool for conversational or user-specific answers, where a cache hit can leak one user's context into another's response.
Conclusion
Treat the LLM like any other external dependency: put it behind an interface, compose cross-cutting concerns in one place, demand typed contracts, and validate everything that comes back. Microsoft.Extensions.AI gives .NET teams exactly that structure with familiar DI and middleware patterns. The result is AI functionality that is testable, observable and replaceable, which is what production code needs to be.