Skip to content
Docs Try Aspire
Docs Try

Set up SQL Server in the AppHost

SQL Server logo

This article is the reference for the Aspire SQL Server Hosting integration. It enumerates the AppHost APIs — with examples for both AppHost.cs and apphost.mts — that you use to model a SQL Server instance and database resources in your AppHost project.

If you’re new to the SQL Server integration, start with the Get started with SQL Server integrations guide. For how consuming apps read the connection information this page exposes, see Connect to SQL Server. For the SQL Server Entity Framework Core (EF Core) client integration, see Get started with the SQL Server EF Core integrations.

To start building an Aspire app that uses SQL Server, install the 📦 Aspire.Hosting.SqlServer NuGet package:

Terminal
aspire add sql-server

Learn more about aspire add in the command reference.

Or, choose a manual installation approach:

C# — AppHost.cs
#:package Aspire.Hosting.SqlServer@*
XML — AppHost.csproj
<PackageReference Include="Aspire.Hosting.SqlServer" Version="*" />

Once you’ve installed the hosting integration in your AppHost project, you can add a SQL Server resource and then add a database resource as shown in the following examples:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithLifetime(ContainerLifetime.Persistent);
var db = sql.AddDatabase("database");
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(db)
.WaitFor(db);
// After adding all resources, run the app...
builder.Build().Run();
  1. When Aspire adds a container image to the AppHost, as shown in the preceding example with the mcr.microsoft.com/mssql/server image, it creates a new SQL Server instance on your local machine. A reference to the database resource is then used to add a dependency to the consuming project.

  2. When adding a database resource to the app model, the database is created if it doesn’t already exist. The creation of the database relies on the AppHost eventing APIs, specifically ResourceReadyEvent. In other words, when the sql resource is ready, the event is raised and the database resource is created.

  3. The SQL Server resource includes default credentials with a username of sa and a randomly generated password using the CreateDefaultPasswordParameter method. The password is stored in the AppHost’s secret store as sql-password.

  4. The AppHost reference call configures a connection in the consuming project named after the referenced database resource, such as database in the preceding example.

Add SQL Server resource with database creation script

Section titled “Add SQL Server resource with database creation script”

By default, when you add a SqlServerDatabaseResource, it relies on the following SQL script to create the database:

SQL — Default database creation script
IF (NOT EXISTS (SELECT 1 FROM sys.databases WHERE name = @DatabaseName))
CREATE DATABASE [<QUOTED_DATABASE_NAME>];

To supply a custom creation script, call WithCreationScript (or withCreationScript) on the database resource builder:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithLifetime(ContainerLifetime.Persistent);
var databaseName = "app-db";
var creationScript = $$"""
IF DB_ID('{{databaseName}}') IS NULL
CREATE DATABASE [{{databaseName}}];
GO
USE [{{databaseName}}];
GO
CREATE TABLE todos (
id INT PRIMARY KEY IDENTITY(1,1),
title VARCHAR(255) NOT NULL,
description TEXT,
is_completed BIT DEFAULT 0,
due_date DATE,
created_at DATETIME DEFAULT GETDATE()
);
GO
""";
var db = sql.AddDatabase(databaseName)
.WithCreationScript(creationScript);
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(db)
.WaitFor(db);
// After adding all resources, run the app...
builder.Build().Run();

The preceding example creates a database named app-db with a single todos table. The script is executed when the database resource is created in the context of the SQL Server resource.

Add a data volume to the SQL Server resource as shown in the following examples:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithDataVolume();
var db = sql.AddDatabase("database");
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(db)
.WaitFor(db);
// After adding all resources, run the app...
builder.Build().Run();

The data volume is used to persist the SQL Server data outside the lifecycle of its container. The data volume is mounted at the /var/opt/mssql path in the SQL Server container and when a name parameter isn’t provided, the name is generated at random. For more information on data volumes and details on why they’re preferred over bind mounts, see Docker docs: Volumes.

Add SQL Server resource with data bind mount

Section titled “Add SQL Server resource with data bind mount”

Add a data bind mount to the SQL Server resource as shown in the following examples:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithDataBindMount(source: @"C:\SqlServer\Data");
var db = sql.AddDatabase("database");
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(db)
.WaitFor(db);
// After adding all resources, run the app...
builder.Build().Run();

Data bind mounts rely on the host machine’s filesystem to persist the SQL Server data across container restarts. The data bind mount is mounted at the C:\SqlServer\Data on Windows (or /SqlServer/Data on Unix) path on the host machine in the SQL Server container. For more information on data bind mounts, see Docker docs: Bind mounts.

When you want to explicitly provide the password used by the container image, you can provide it as a parameter:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var password = builder.AddParameter("password", secret: true);
var sql = builder.AddSqlServer("sql", password);
var db = sql.AddDatabase("database");
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(db)
.WaitFor(db);
// After adding all resources, run the app...
builder.Build().Run();

When no password parameter is provided, Aspire generates a strong password automatically using the CreateDefaultPasswordParameter method. For more information on providing parameters, see External parameters.

Use a specific SQL Server container image tag

Section titled “Use a specific SQL Server container image tag”

To pin the SQL Server container to a specific release, call WithImageTag (or withImageTag):

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql")
.WithImageTag("2025-RTM-ubuntu-24.04-preview");
var db = sql.AddDatabase("database");
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(db)
.WaitFor(db);
// After adding all resources, run the app...
builder.Build().Run();

For a list of available tags, see SQL Server container image tags.

By default, Aspire injects the SQL Server connection information using variable names derived from the resource name (for example, DATABASE_URI, DATABASE_HOST, DATABASE_PORT). If your consuming app expects a different set of environment variable names, pass individual connection properties from the AppHost:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddSqlServer("sql");
var database = sql.AddDatabase("database");
var app = builder.AddExecutable("my-app", "node", "app.js", ".")
.WithReference(database)
.WithEnvironment(context =>
{
context.EnvironmentVariables["SQL_HOST"] = sql.Resource.PrimaryEndpoint.Property(EndpointProperty.Host);
context.EnvironmentVariables["SQL_PORT"] = sql.Resource.PrimaryEndpoint.Property(EndpointProperty.Port);
context.EnvironmentVariables["SQL_PASSWORD"] = sql.Resource.PasswordParameter;
context.EnvironmentVariables["SQL_DATABASE"] = database.Resource.DatabaseName;
});
builder.Build().Run();

Connect to an existing SQL Server instance

Section titled “Connect to an existing SQL Server instance”

To reference an externally managed SQL Server instance instead of running one as a container, use AddConnectionString:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var sql = builder.AddConnectionString("sql");
var exampleProject = builder.AddProject<Projects.ExampleProject>("exampleproject")
.WithReference(sql);
// After adding all resources, run the app...
builder.Build().Run();

The connection string is resolved from the ConnectionStrings configuration section of the AppHost project:

JSON — appsettings.json
{
"ConnectionStrings": {
"sql": "Server=myserver;Database=mydb;User Id=sa;Password=mypassword;"
}
}

For more information, see Reference existing resources.

When the AppHost runs, the server’s database resources can be accessed from external tools, such as SQL Server Management Studio (SSMS) or MSSQL for Visual Studio Code. The connection string for the database resource is available in the dependent resources environment variables and is accessed using the Aspire dashboard: Resource details pane. The environment variable is named ConnectionStrings__{name} where {name} is the name of the database resource, in this example it’s database. Use the connection string to connect to the database resource from external tools.

To connect to the database resource from SQL Server Management Studio, follow these steps:

  1. Open SSMS.

  2. In the Connect to Server dialog, select the Additional Connection Parameters tab.

  3. Paste the connection string into the Additional Connection Parameters field and select Connect.

    SQL Server Management Studio: Connect to Server dialog.

  4. If you’re connected, you can see the database resource in the Object Explorer:

    SQL Server Management Studio: Connected to database.

For the full reference of SQL Server connection properties — and how consuming apps in C#, TypeScript, Python, and Go read them — see Connect to SQL Server.

The SQL Server hosting integration automatically adds a health check for the SQL Server resource. The health check verifies that the SQL Server instance is running and that a connection can be established to it.

The hosting integration relies on the 📦 AspNetCore.HealthChecks.SqlServer NuGet package.