Connect to SQL Server
Este conteúdo não está disponível em sua língua ainda.
This page describes how consuming apps connect to a SQL Server resource that’s already modeled in your AppHost. For the AppHost API surface — adding a SQL Server instance, databases, data volumes, bind mounts, and more — see SQL Server Hosting integration.
When you reference a SQL Server resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire SQL Server client integration for automatic dependency injection, health checks, and telemetry.
Connection properties
Section titled “Connection properties”Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called sqldb becomes SQLDB_URI.
SQL Server server resource
Section titled “SQL Server server resource”The SQL Server server resource exposes the following connection properties:
| Property Name | Description |
|---|---|
Host | The hostname or IP address of the SQL Server instance |
Port | The port number the SQL Server instance is listening on |
Username | The username for authentication |
Password | The password for authentication |
Uri | The connection URI in mssql:// format, with the format mssql://{Username}:{Password}@{Host}:{Port} |
JdbcConnectionString | JDBC-format connection string, with the format jdbc:sqlserver://{Host}:{Port};trustServerCertificate=true. User and password credentials are provided as separate Username and Password properties. |
Example connection strings:
Uri: mssql://sa:p%40ssw0rd1@localhost:1433JdbcConnectionString: jdbc:sqlserver://localhost:1433;trustServerCertificate=trueSQL Server database resource
Section titled “SQL Server database resource”The SQL Server database resource inherits all properties from its parent server resource and adds:
| Property Name | Description |
|---|---|
Uri | The connection URI with the database name, with the format mssql://{Username}:{Password}@{Host}:{Port}/{DatabaseName} |
JdbcConnectionString | JDBC connection string with the database name, with the format jdbc:sqlserver://{Host}:{Port};trustServerCertificate=true;databaseName={DatabaseName}. User and password credentials are provided as separate Username and Password properties. |
Database | The name of the database |
Example connection strings:
Uri: mssql://sa:p%40ssw0rd1@localhost:1433/catalogJdbcConnectionString: jdbc:sqlserver://localhost:1433;trustServerCertificate=true;databaseName=catalogConnect from your app
Section titled “Connect from your app”Pick the language your consuming app is written in. Each example assumes your AppHost adds a SQL Server database resource named sqldb and references it from the consuming app.
For C# apps, the recommended approach is the Aspire SQL Server client integration. It registers a SqlConnection through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.
Install the client integration
Section titled “Install the client integration”Install the 📦 Aspire.Microsoft.Data.SqlClient NuGet package in the client-consuming project:
dotnet add package Aspire.Microsoft.Data.SqlClient#:package Aspire.Microsoft.Data.SqlClient@*<PackageReference Include="Aspire.Microsoft.Data.SqlClient" Version="*" />Add the SQL Server client
Section titled “Add the SQL Server client”In Program.cs, call AddSqlServerClient on your IHostApplicationBuilder to register a SqlConnection:
builder.AddSqlServerClient(connectionName: "sqldb");Resolve the connection through dependency injection:
public class ExampleService(SqlConnection connection){ // Use connection...}For more information on dependency injection, see .NET dependency injection.
Add keyed SQL Server clients
Section titled “Add keyed SQL Server clients”To register multiple SqlConnection instances with different connection names, use AddKeyedSqlServerClient:
builder.AddKeyedSqlServerClient(name: "mainDb");builder.AddKeyedSqlServerClient(name: "loggingDb");Then resolve each instance by key:
public class ExampleService( [FromKeyedServices("mainDb")] SqlConnection mainDbConnection, [FromKeyedServices("loggingDb")] SqlConnection loggingDbConnection){ // Use connections...}For more information on keyed services, see .NET dependency injection: Keyed services.
Configuration
Section titled “Configuration”The Aspire SQL Server client integration offers multiple ways to provide configuration.
Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddSqlServerClient:
builder.AddSqlServerClient("sqldb");The connection string is resolved from the ConnectionStrings section:
{ "ConnectionStrings": { "sqldb": "Data Source=myserver;Initial Catalog=sqldb" }}For more information on connection string format, see SqlConnection.ConnectionString.
Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads MicrosoftDataSqlClientSettings from appsettings.json (or any other configuration source) by using the Aspire:Microsoft:Data:SqlClient key:
{ "Aspire": { "Microsoft": { "Data": { "SqlClient": { "ConnectionString": "Data Source=myserver;Initial Catalog=sqldb", "DisableHealthChecks": false, "DisableMetrics": false } } } }}For the complete SQL Server client integration JSON schema, see Aspire.Microsoft.Data.SqlClient/ConfigurationSchema.json.
Inline delegates. Pass an Action<MicrosoftDataSqlClientSettings> to configure settings inline, for example to disable health checks:
builder.AddSqlServerClient( "sqldb", static settings => settings.DisableHealthChecks = true);Client integration health checks
Section titled “Client integration health checks”Aspire client integrations enable health checks by default. The SQL Server client integration adds:
- A health check that attempts to connect to the SQL Server instance and execute a command.
- Integration with the
/healthHTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.
Observability and telemetry
Section titled “Observability and telemetry”The Aspire SQL Server client integration automatically configures logging, tracing, and metrics through OpenTelemetry.
Logging: The SQL Server client integration currently doesn’t enable logging by default due to limitations of the SqlClient.
Tracing activities:
OpenTelemetry.Instrumentation.SqlClient
Metrics from Microsoft.Data.SqlClient.EventSource:
active-hard-connectionshard-connectshard-disconnectsactive-soft-connectssoft-connectssoft-disconnectsnumber-of-non-pooled-connectionsnumber-of-pooled-connectionsnumber-of-active-connection-pool-groupsnumber-of-inactive-connection-pool-groupsnumber-of-active-connection-poolsnumber-of-inactive-connection-poolsnumber-of-active-connectionsnumber-of-free-connectionsnumber-of-stasis-connectionsnumber-of-reclaimed-connections
Any of these telemetry features can be disabled through the configuration options above.
Read environment variables in C#
Section titled “Read environment variables in C#”If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and open a connection using 📦 Microsoft.Data.SqlClient:
using Microsoft.Data.SqlClient;
var connectionString = Environment.GetEnvironmentVariable("SQLDB_URI");
await using var connection = new SqlConnection(connectionString);await connection.OpenAsync();
// Use connection to query the database...Use the microsoft/go-mssqldb driver, Microsoft’s officially maintained Go driver for SQL Server:
go get github.com/microsoft/go-mssqldbRead the injected environment variable and connect:
package main
import ( "context" "database/sql" "os"
_ "github.com/microsoft/go-mssqldb")
func main() { // Read the Aspire-injected connection URI connStr := os.Getenv("SQLDB_URI")
db, err := sql.Open("mssql", connStr) if err != nil { panic(err) } defer db.Close()
if err := db.PingContext(context.Background()); err != nil { panic(err) }}Install pyodbc and the Microsoft ODBC Driver 18 for SQL Server:
pip install pyodbcRead the injected environment variables and connect:
import osimport pyodbc
# Read Aspire-injected connection propertiessql_host = os.getenv("SQLDB_HOST")sql_port = os.getenv("SQLDB_PORT", "1433")sql_user = os.getenv("SQLDB_USERNAME")sql_password = os.getenv("SQLDB_PASSWORD")sql_database = os.getenv("SQLDB_DATABASE")
connection_string = ( f"DRIVER={{ODBC Driver 18 for SQL Server}};" f"SERVER={sql_host},{sql_port};" f"DATABASE={sql_database};" f"UID={sql_user};" f"PWD={sql_password};")
conn = pyodbc.connect(connection_string)cursor = conn.cursor()
# Use cursor to query the database...Or use the connection URI directly:
import osimport pyodbc
# Read the Aspire-injected connection URIuri = os.getenv("SQLDB_URI")
# pyodbc requires an ODBC-style connection string — build it from the URI# or use individual properties as shown aboveInstall the mssql npm package, the most popular SQL Server client for Node.js:
npm install mssqlnpm install --save-dev @types/mssqlRead the injected environment variables and connect:
import sql from 'mssql';
// Read Aspire-injected connection propertiesconst config: sql.config = { server: process.env.SQLDB_HOST!, port: Number(process.env.SQLDB_PORT), user: process.env.SQLDB_USERNAME, password: process.env.SQLDB_PASSWORD, database: process.env.SQLDB_DATABASE, options: { trustServerCertificate: true, },};
const pool = await sql.connect(config);
// Use pool to query the database...Or use the connection URI directly:
import sql from 'mssql';
const pool = await sql.connect(process.env.SQLDB_URI!);