Local language models are becoming a practical option for applications that need AI capabilities without depending entirely on cloud-based AI services. With tools such as Ollama, developers can download models, run them locally, and connect them to .NET applications through HTTP APIs.
However, local AI introduces a deployment challenge that traditional .NET applications do not usually have: model files can be extremely large.
A typical .NET application contains compiled assemblies, configuration files, dependencies, and other application resources. A local AI model may require several gigabytes of additional storage. If developers place model files inside the application directory and include them in the publishing process, every deployment can become unnecessarily large.
This creates problems with build times, deployment packages, storage consumption, application updates, and release management.
A better approach is to separate application deployment from model deployment. The .NET application should contain the code required to communicate with the model, while the model files should be managed independently by the AI runtime or infrastructure.
In this article, we will explore how to keep local AI model files out of .NET deployment packages, configure external model storage, organize application configuration, and prepare a deployment architecture that allows models to be updated without rebuilding the application.
Why Should AI Model Files Be Kept Outside the Application?
Consider a .NET application that uses a local Llama model through Ollama.
A simple project might initially look like this:
LocalAIApplication/
│
├── LocalAIApplication.csproj
├── Program.cs
├── appsettings.json
│
└── Models/
├── model-part-01
├── model-part-02
└── model-part-03
At first, keeping the model files alongside the application may seem convenient. Developers can manage everything in one directory and copy the complete folder during deployment.
However, this approach creates several problems.
Large Deployment Packages
AI model files can occupy significantly more disk space than application binaries.
When model files are included in the publishing output, the deployment package becomes much larger than necessary.
For example, assume an application contains:
Component | Example Size |
|---|
.NET application and dependencies | 80 MB |
Configuration and supporting files | 5 MB |
Local AI model | 5 GB |
The application itself needs approximately 85 MB, but including the model increases the deployment package to more than 5 GB.
These figures are illustrative, but they show why model storage should be managed separately.
Slower Application Deployments
When model files are copied with every release, deployment systems must transfer and process files that may not have changed.
This increases deployment duration and creates unnecessary storage and network usage.
It also makes application rollback more complicated because the deployment process may need to restore large model files even when only application code changed.
Unnecessary Storage Duplication
Suppose an organization runs three instances of the same .NET application.
If every deployment contains its own copy of the model, the same model files may be stored three times.
A better design allows the AI runtime to manage the model files independently from the application instances.
Difficult Model Updates
Application code and AI models do not necessarily need to be updated together.
For example, developers may want to upgrade a language model while keeping the existing application version unchanged.
Separating model storage allows these operations to happen independently, subject to compatibility testing.
Understanding the Recommended Architecture
The most important design decision is to separate the application lifecycle from the model lifecycle.
The .NET application should communicate with an AI runtime rather than directly managing model files.
A recommended architecture looks like this:
.NET Application
|
v
AI Client Layer
|
v
Local AI Runtime
Ollama
|
v
External Model Storage
|
v
Local LLM Files
Each component has a separate responsibility.
Component | Responsibility |
|---|
.NET application | Handles business logic and AI requests |
AI client | Communicates with the model runtime |
Ollama | Loads and executes the selected model |
Model storage | Stores downloaded model files |
Configuration | Identifies the runtime endpoint and model name |
The application does not need to know where the model files are physically stored.
It only needs to know the model name and the endpoint exposed by the AI runtime.
This separation makes deployments smaller and simplifies model management.
Understanding How Ollama Stores Model Files
Ollama manages downloaded models separately from the application that consumes them.
Its default model storage locations are different across operating systems.
Operating System | Default Model Location |
|---|
macOS | ~/.ollama/models |
Linux | /usr/share/ollama/.ollama/models |
Windows | C:\Users\username.ollama\models |
The model directory contains internal storage structures, including model manifests and data blobs.
Developers should generally avoid manually modifying these internal files. Ollama manages the model storage structure and uses it when loading models.
If you want to move models to another location, Ollama provides the OLLAMA_MODELS environment variable.
This allows model storage to be configured independently from the application directory.
Moving Model Storage Outside the Default Directory
For machines with limited system storage, it may be useful to place model files on a separate disk or dedicated storage volume.
For example, an organization may want to store models in:
D:\AI\Models
On Windows, configure the OLLAMA_MODELS environment variable with the new directory.
You can set it from PowerShell:
[Environment]::SetEnvironmentVariable(
"OLLAMA_MODELS",
"D:\AI\Models",
"User"
)
After changing the environment variable, restart the Ollama application so that it receives the updated configuration.
On Linux, if Ollama runs as a systemd service, configure the environment variable through a service override.
Create or edit the service override:
sudo systemctl edit ollama.service
Add the following configuration:
[Service]
Environment="OLLAMA_MODELS=/data/ai-models"
Reload systemd and restart Ollama:
sudo systemctl daemon-reload
sudo systemctl restart ollama
Make sure the Ollama service account has permission to read and write to the configured directory.
On macOS, environment variables for an Ollama application running as a macOS app can be configured using launchctl.
For example:
launchctl setenv OLLAMA_MODELS "/Volumes/AIModels"
Restart the Ollama application after setting the variable.
The exact configuration depends on how Ollama is installed and started. Setting an environment variable in a terminal does not automatically guarantee that an already running desktop application or system service will receive it.
Keeping Model Files Out of the .NET Project
Moving model storage is only one part of the solution. Developers should also ensure that model files are not accidentally included in the .NET publishing process.
The simplest approach is to keep model files outside the application source directory.
For example:
Development/
│
├── LocalAIApplication/
│ ├── LocalAIApplication.csproj
│ ├── Program.cs
│ └── appsettings.json
│
└── AIModels/
└── ManagedByOllama/
This structure makes the separation clear.
The .NET project contains application code, while the model runtime manages model storage independently.
Avoid copying downloaded model files into folders such as bin, obj, or the project root.
Excluding Model Files Through the Project File
Sometimes model files are already present inside a project directory.
In that case, developers should explicitly prevent those files from being included in the application build and publishing output.
Consider the following project configuration:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<Content Remove="LocalModels\**\*" />
<None Remove="LocalModels\**\*" />
</ItemGroup>
</Project>
The Content and None removal entries prevent files under LocalModels from being included through the corresponding default project item groups.
This is useful when a project directory contains development-only assets that should not be part of the application.
If a model file is explicitly included through another project item group or imported build configuration, review that configuration as well.
For files that are intentionally included as content but should never be copied to deployment output, use explicit metadata:
<ItemGroup>
<Content Update="LocalModels\**\*">
<CopyToOutputDirectory>Never</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</Content>
</ItemGroup>
The important difference is that Remove excludes an item from the project item group, while the copy metadata controls whether an included content item is copied to output or publish directories.
Do not rely only on the absence of model files in the current publish folder. Review the project file and build configuration to make sure future changes do not accidentally include them.
Configuring the .NET Application to Use an External Model
Once model storage is managed independently, the .NET application needs only the AI runtime endpoint and model identifier.
For example, configure appsettings.json as follows:
{
"AI": {
"Endpoint": "http://localhost:11434",
"Model": "llama3.2"
}
}
Notice that the configuration does not contain a physical model file path.
This is intentional.
The application communicates with Ollama, and Ollama manages the model files.
This also makes it possible to move model storage without changing the application configuration.
Creating the AI Client
Install the required packages:
dotnet add package Microsoft.Extensions.AI
dotnet add package OllamaSharp
Now create a small service that reads the model configuration and initializes the local AI client.
using Microsoft.Extensions.AI;
using OllamaSharp;
public sealed class LocalAIService
{
private readonly IChatClient _chatClient;
public LocalAIService(IConfiguration configuration)
{
string endpoint =
configuration["AI:Endpoint"]
?? throw new InvalidOperationException(
"AI endpoint is not configured.");
string model =
configuration["AI:Model"]
?? throw new InvalidOperationException(
"AI model is not configured.");
_chatClient = new OllamaApiClient(
new Uri(endpoint),
model
);
}
public async Task<string> AskAsync(
string prompt,
CancellationToken cancellationToken = default)
{
ChatResponse response =
await _chatClient.GetResponseAsync(
prompt,
cancellationToken: cancellationToken
);
return response.Text;
}
}
The service does not access the model directory or load model files directly.
It sends requests to the configured Ollama endpoint.
This keeps the application independent of the model storage implementation.
For production applications, register the client through dependency injection and manage its lifetime appropriately rather than creating new clients for individual requests.
Publishing the .NET Application Without Model Files
After separating model storage, publish the application normally.
For example:
dotnet publish -c Release -r win-x64
The output contains the application assemblies, runtime dependencies where applicable, and configuration files required by the deployment.
It should not contain the large model files managed by Ollama.
For a self-contained deployment, you can use:
dotnet publish -c Release -r win-x64 --self-contained true
A self-contained deployment includes the .NET runtime components required by the application, but it does not automatically require AI model files to be included.
It is important to understand that single-file publishing and model storage are separate concerns.
Publishing an application as a single executable does not mean that every external resource must be embedded into that executable.
If the application includes other external resources, manage their publishing behavior explicitly.
Managing Models During Deployment
Keeping model files outside the application package does not eliminate the need to prepare them on the target machine.
The deployment environment must have access to the required model before the application starts processing AI requests.
A practical deployment workflow should separate application deployment from model provisioning.
Prepare the AI Runtime
Install Ollama or the selected model runtime on the target machine.
Configure its service account, storage directory, and network access according to the environment.
For a production server, consider running the AI runtime as a managed service rather than relying on an interactive desktop session.
Download the Required Model
Download the model during environment preparation:
ollama pull llama3.2
This operation should happen during infrastructure provisioning or a controlled model update process, not every time the .NET application starts.
Repeatedly downloading a large model during application startup can increase deployment time and introduce unnecessary network dependencies.
Verify Model Availability
Before deploying the application, verify that the expected model is installed:
ollama list
You can also check the runtime's model API or execute a small test request.
This helps detect missing models before the application receives production traffic.
Deploy the .NET Application
Publish and deploy the application independently.
The application should use the configured Ollama endpoint and model name.
This allows application releases and model updates to follow separate schedules.
Using Docker Without Packaging Model Files
Containerization introduces another important deployment consideration.
A common mistake is copying large model files directly into the Docker image.
For example, the following approach should generally be avoided:
FROM mcr.microsoft.com/dotnet/aspnet:10.0
WORKDIR /app
COPY publish/ .
COPY Models/ /app/Models/
ENTRYPOINT ["dotnet", "LocalAIApplication.dll"]
The second COPY instruction places model files inside the application image.
This increases image size and causes unnecessary image transfers whenever the image is built or deployed.
Instead, keep the .NET application and AI runtime in separate containers.
A simplified Docker Compose configuration could look like this:
services:
ai-runtime:
image: ollama/ollama
volumes:
- ollama-models:/root/.ollama
ports:
- "127.0.0.1:11434:11434"
dotnet-app:
build: .
environment:
AI__Endpoint: http://ai-runtime:11434
AI__Model: llama3.2
depends_on:
- ai-runtime
volumes:
ollama-models:
In this example, Ollama manages model storage through a Docker volume.
The .NET application communicates with the Ollama service using the Docker Compose service name.
The volume persists model data independently of the application container.
The port binding limits host access to the loopback interface. The .NET application can still communicate with Ollama over the internal Compose network.
For production environments, review network isolation, authentication, resource limits, container permissions, health checks, and persistent volume configuration.
Also remember that depends_on controls service startup ordering, not necessarily model readiness. The application should implement connection retries or readiness checks before sending inference requests.
Common Mistakes to Avoid
Mistake | Why It Causes Problems | Recommended Approach |
|---|
Storing models inside the project directory | Model files may enter build or publish output | Use external model storage |
Copying models into Docker images | Increases image size and deployment time | Use persistent volumes |
Downloading models during application startup | Creates startup delays and network dependency | Provision models separately |
Hardcoding model directories | Makes infrastructure changes difficult | Configure storage in the AI runtime |
Sharing model storage without access controls | Can expose model files to unauthorized processes | Apply filesystem permissions |
Updating models without testing | May change response quality or compatibility | Validate new model versions before rollout |
Assuming a model is installed | Application requests may fail at runtime | Add model availability checks |
Deleting storage during deployment cleanup | Can remove models required by the application | Keep model storage outside disposable deployment directories |
Advantages and Disadvantages of External Model Storage
Advantages
Keeps .NET deployment packages small.
Reduces unnecessary model file transfers.
Allows application and model updates to happen independently.
Supports persistent model storage across container replacements.
Makes infrastructure and deployment management easier.
Reduces duplicated model files across application releases.
Allows model storage to use dedicated disks or volumes.
Disadvantages
Requires additional infrastructure configuration.
The application depends on a separately managed AI runtime.
Model availability must be verified during deployment.
Storage permissions need to be managed carefully.
Model updates require their own validation and release process.
Backup and recovery procedures must cover model storage separately when required.
Summary
Local AI models introduce storage and deployment requirements that are different from traditional .NET application dependencies.
Including large model files inside application packages increases deployment size, slows releases, and makes model updates unnecessarily dependent on application releases.
A better architecture separates the .NET application from the AI runtime and model storage. Ollama can manage downloaded models independently through its default storage directory or the OLLAMA_MODELS environment variable.
In this article, we explored how to configure external model storage, exclude model files from .NET publishing, configure an application to use a local model endpoint, and manage persistent model storage in Docker.
The key principle is to treat application binaries and AI models as separate deployment artifacts. This makes .NET applications easier to deploy, update, scale, and maintain while keeping local AI infrastructure under control.
Join the conversation! Your thoughts help the community grow.