跳转到内容
Docs Try Aspire
Docs Try

Connect to SQL Server

此内容尚不支持你的语言。

SQL Server logo

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.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called sqldb becomes SQLDB_URI.

The SQL Server server resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the SQL Server instance
PortThe port number the SQL Server instance is listening on
UsernameThe username for authentication
PasswordThe password for authentication
UriThe connection URI in mssql:// format, with the format mssql://{Username}:{Password}@{Host}:{Port}
JdbcConnectionStringJDBC-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:1433
JdbcConnectionString: jdbc:sqlserver://localhost:1433;trustServerCertificate=true

The SQL Server database resource inherits all properties from its parent server resource and adds:

Property NameDescription
UriThe connection URI with the database name, with the format mssql://{Username}:{Password}@{Host}:{Port}/{DatabaseName}
JdbcConnectionStringJDBC 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.
DatabaseThe name of the database

Example connection strings:

Uri: mssql://sa:p%40ssw0rd1@localhost:1433/catalog
JdbcConnectionString: jdbc:sqlserver://localhost:1433;trustServerCertificate=true;databaseName=catalog

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 📦 Aspire.Microsoft.Data.SqlClient NuGet package in the client-consuming project:

.NET CLI — Add Aspire.Microsoft.Data.SqlClient package
dotnet add package Aspire.Microsoft.Data.SqlClient

In Program.cs, call AddSqlServerClient on your IHostApplicationBuilder to register a SqlConnection:

C# — Program.cs
builder.AddSqlServerClient(connectionName: "sqldb");

Resolve the connection through dependency injection:

C# — ExampleService.cs
public class ExampleService(SqlConnection connection)
{
// Use connection...
}

For more information on dependency injection, see .NET dependency injection.

To register multiple SqlConnection instances with different connection names, use AddKeyedSqlServerClient:

C# — Program.cs
builder.AddKeyedSqlServerClient(name: "mainDb");
builder.AddKeyedSqlServerClient(name: "loggingDb");

Then resolve each instance by key:

C# — ExampleService.cs
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.

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:

C# — Program.cs
builder.AddSqlServerClient("sqldb");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"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:

JSON — appsettings.json
{
"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:

C# — Program.cs
builder.AddSqlServerClient(
"sqldb",
static settings => settings.DisableHealthChecks = true);

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 /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

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-connections
  • hard-connects
  • hard-disconnects
  • active-soft-connects
  • soft-connects
  • soft-disconnects
  • number-of-non-pooled-connections
  • number-of-pooled-connections
  • number-of-active-connection-pool-groups
  • number-of-inactive-connection-pool-groups
  • number-of-active-connection-pools
  • number-of-inactive-connection-pools
  • number-of-active-connections
  • number-of-free-connections
  • number-of-stasis-connections
  • number-of-reclaimed-connections

Any of these telemetry features can be disabled through the configuration options above.

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:

C# — Program.cs
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...