AI applications often begin with a single model provider. A developer connects an application to a local model, tests a few prompts, and starts building features around the model's response.
Over time, application requirements may change. The team may decide to move from a local model to a cloud provider, introduce a second provider for specific workloads, or switch providers because of cost, performance, availability, or business requirements.
This change can become difficult when the application is tightly connected to a provider-specific SDK. Model initialization, request options, response handling, streaming, tool calling, and error handling may all depend on the original provider.
A better approach is to separate application logic from the AI provider.
In .NET, Microsoft.Extensions.AI provides abstractions such as IChatClient that help developers build applications without making the application layer depend directly on one model provider.
In this article, we will explore how to build provider-independent AI features in ASP.NET Core, configure different providers, switch between them through configuration, and identify the differences that still need attention when changing models.
Why AI Provider Independence Matters
Imagine an ASP.NET Core application that uses a local Llama model through Ollama.
The application contains an AI-powered support assistant. It accepts questions, sends them to the model, and returns the generated response.
Initially, the application may use provider-specific code:
using OllamaSharp;
var client = new OllamaApiClient(
new Uri("http://localhost:11434"),
"llama3.2"
);
var response = await client.GenerateAsync(
"Explain dependency injection in .NET."
);This code works with Ollama, but the application now depends on OllamaSharp and its specific API.
If the team decides to use an OpenAI model, it must introduce another SDK and update the code that communicates with the model.
As provider-specific code spreads across controllers, services, and business logic, changing providers becomes more expensive.
Consider the following differences:
Application Area | Provider-Specific Implementation | Provider-Independent Approach |
|---|---|---|
Client initialization | Provider SDK | IChatClient |
Sending prompts | Provider-specific methods | GetResponseAsync |
Streaming | Provider-specific streaming API | GetStreamingResponseAsync |
Tool calling | Provider-specific function definitions | AIFunction and tool abstractions |
Configuration | SDK settings throughout the application | Centralized configuration |
Testing | Provider-dependent tests | Mock or fake IChatClient |
Provider switching | Multiple code changes | Change provider registration and configuration |
Provider independence does not mean every model behaves identically. It means the application has a consistent interface for communicating with different providers.
Understanding Microsoft.Extensions.AI
Microsoft.Extensions.AI provides a common set of abstractions for working with AI services in .NET applications.
Its most important abstraction for chat-based applications is IChatClient.
IChatClient defines a common interface for sending messages and receiving responses from AI models. It supports both complete responses and streaming responses.
Different libraries can implement this interface for different providers.
For example:
OllamaSharp provides an implementation for local Ollama models.
Microsoft.Extensions.AI.OpenAI provides integration with OpenAI-compatible chat clients.
Other AI libraries can provide their own IChatClient implementations.
The application can depend on IChatClient instead of directly referencing a provider-specific client.
The architecture becomes:
ASP.NET Core API
|
v
Application Services
|
v
IChatClient
|
v
Provider Registration
|
+------------------+
| |
v v
Ollama OpenAI
| |
v v
Local Model Cloud ModelThe application service does not need to know which provider is being used.
This abstraction also supports middleware for capabilities such as function invocation, caching, logging, and telemetry.
Creating the ASP.NET Core Project
Let's build a small application that can communicate with either Ollama or OpenAI.
Create a new project:
dotnet new web -n ProviderIndependentAI
cd ProviderIndependentAIInstall the required packages:
dotnet add package Microsoft.Extensions.AI
dotnet add package OllamaSharp
dotnet add package Microsoft.Extensions.AI.OpenAIThe application uses Microsoft.Extensions.AI as the common abstraction, OllamaSharp for the local provider, and Microsoft.Extensions.AI.OpenAI for OpenAI integration.
Keep provider-specific packages in the infrastructure layer of a larger solution. The application services should reference Microsoft.Extensions.AI abstractions rather than provider SDKs.
Creating a Centralized AI Configuration
The first step is to avoid hardcoding provider information in application services.
Create an appsettings.json file with the following configuration:
{
"AI": {
"Provider": "Ollama",
"Model": "llama3.2",
"Ollama": {
"Endpoint": "http://localhost:11434"
},
"OpenAI": {
"Model": "gpt-4o-mini"
}
}
}The Provider property determines which AI provider the application uses.
When Provider is Ollama, the application connects to a local model server. When Provider is OpenAI, it creates an OpenAI chat client.
The model name is also configured separately so that changing the selected model does not require modifying application services.
For production applications, keep API keys in a secure configuration provider, such as environment variables, a managed secret store, or another approved secrets-management system. Do not store production API keys in a committed appsettings.json file.
Creating an AI Options Class
Create a class named AIOptions.cs:
public sealed class AIOptions
{
public string Provider { get; set; } = "Ollama";
public string Model { get; set; } = "llama3.2";
public OllamaOptions Ollama { get; set; } = new();
public OpenAIOptions OpenAI { get; set; } = new();
}
public sealed class OllamaOptions
{
public string Endpoint { get; set; } =
"http://localhost:11434";
}
public sealed class OpenAIOptions
{
public string Model { get; set; } = "gpt-4o-mini";
}This class maps the AI configuration into strongly typed objects.
Using typed configuration makes it easier to validate settings and reduces the need to read configuration values directly from controllers or business services.
Registering Different AI Providers
Now create a provider registration method.
The purpose of this method is to create the appropriate IChatClient implementation based on configuration.
Add the following code to Program.cs:
using Microsoft.Extensions.AI;
using Microsoft.Extensions.Options;
using OllamaSharp;
using OpenAI.Chat;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<AIOptions>(
builder.Configuration.GetSection("AI")
);
builder.Services.AddSingleton<IChatClient>(serviceProvider =>
{
var options = serviceProvider
.GetRequiredService<IOptions<AIOptions>>()
.Value;
IChatClient client;
switch (options.Provider.ToLowerInvariant())
{
case "ollama":
client = new OllamaApiClient(
new Uri(options.Ollama.Endpoint),
options.Model
);
break;
case "openai":
var apiKey = builder.Configuration[
"AI:OpenAI:ApiKey"
];
if (string.IsNullOrWhiteSpace(apiKey))
{
throw new InvalidOperationException(
"OpenAI API key is not configured."
);
}
client = new ChatClient(
options.OpenAI.Model,
apiKey
).AsIChatClient();
break;
default:
throw new InvalidOperationException(
$"Unsupported AI provider: {options.Provider}"
);
}
return client;
});
builder.Services.AddScoped<AIService>();
var app = builder.Build();
app.MapPost(
"/api/ai/ask",
async (
AskRequest request,
AIService aiService,
CancellationToken cancellationToken) =>
{
if (string.IsNullOrWhiteSpace(request.Message))
{
return Results.BadRequest(
new { error = "Message is required." }
);
}
var response = await aiService.AskAsync(
request.Message,
cancellationToken
);
return Results.Ok(new
{
answer = response
});
}
);
app.Run();
public sealed record AskRequest(string Message);
Join the conversation! Your thoughts help the community grow.