Edit

Share via


.NET Aspire Azure SQL integration

Includes: Hosting integration included Hosting integration —&— Client integration included Client integration

Azure SQL is a family of relational database management systems that run in the Azure cloud. The database systems are Platform-as-a-Service (PaaS) products that enable database administrators to implement highly scalable and available databases without maintaining complex infrastructures themselves. The .NET Aspire Azure SQL Server Hosting integration provides methods to create a new Azure Database server and databases from code in your .NET Aspire app host project. In a consuming project, you can use the .NET Aspire SQL Server client integration as you would for any other SQL Server instance.

Hosting integration

The Azure SQL hosting integration models the Azure SQL server as the AzureSqlServerResource type and the database as the AzureSqlDatabaseResource type. To access these types and APIs, add the 📦 Aspire.Hosting.Azure.Sql NuGet package in the app host project.

dotnet add package Aspire.Hosting.Azure.Sql

For more information, see dotnet add package or Manage package dependencies in .NET applications.

The Azure SQL hosting integration takes a dependency on the 📦 Aspire.Hosting.SqlServer NuGet package, extending it to support Azure. Everything that you can do with the .NET Aspire SQL Server integration and .NET Aspire SQL Server Entity Framework Core integration you can also do with this integration.

Add Azure SQL server resource and database resource

In your app host project, call AddAzureSqlServer to add and return an Azure SQL server resource builder. Chain a call to the returned resource builder to AddDatabase, to add an Azure SQL database resource:

var azureSql = builder.AddAzureSqlServer("azuresql")
                      .AddDatabase("database");

var myService = builder.AddProject<Projects.MyService>()
                       .WithReference(azureSql);

The preceding call to AddAzureSqlServer configures the Azure SQL server resource to be deployed as an Azure SQL Database server.

Important

By default, AddAzureSqlServer configures Microsoft Entra ID authentication. This requires changes to applications that need to connect to these resources. For more information, see Client integration.

Tip

When you call AddAzureSqlServer, it implicitly calls AddAzureProvisioning — which adds support for generating Azure resources dynamically during app startup. The app must configure the appropriate subscription and location. For more information, see Local provisioning: Configuration.

Connect to an existing Azure SQL server

You might have an existing Azure SQL Database service that you want to connect to. You can chain a call to annotate that your AzureSqlServerResource is an existing resource:

var builder = DistributedApplication.CreateBuilder(args);

var existingSqlServerName = builder.AddParameter("existingSqlServerName");
var existingSqlServerResourceGroup = builder.AddParameter("existingSqlServerResourceGroup");

var sqlserver = builder.AddAzureSqlServer("sqlserver")
                       .AsExisting(existingSqlServerName, existingSqlServerResourceGroup)
                       .AddDatabase("database");

builder.AddProject<Projects.ExampleProject>()
       .WithReference(sqlserver);

// After adding all resources, run the app...

For more information on treating Azure SQL Database resources as existing resources, see Use existing Azure resources.

Note

Alternatively, instead of representing an Azure SQL Database resource, you can add a connection string to the app host. This approach is weakly-typed, and doesn't work with role assignments or infrastructure customizations. For more information, see Add existing Azure resources with connection strings.

Run Azure SQL server resource as a container

The Azure SQL Server hosting integration supports running the Azure SQL server as a local container. This is beneficial for situations where you want to run the Azure SQL server locally for development and testing purposes, avoiding the need to provision an Azure resource or connect to an existing Azure SQL server.

To run the Azure SQL server as a container, call the RunAsContainer method:

var builder = DistributedApplication.CreateBuilder(args);

var azureSql = builder.AddAzureSqlServer("azuresql")
                      .RunAsContainer();

var azureSqlData = azureSql.AddDatabase("database");

var exampleProject = builder.AddProject<Projects.ExampleProject>()
                            .WithReference(azureSqlData);

The preceding code configures an Azure SQL Database resource to run locally in a container.

Tip

The RunAsContainer method is useful for local development and testing. The API exposes an optional delegate that enables you to customize the underlying SqlServerServerResource configuration. For example, you can add a data volume or data bind mount. For more information, see the .NET Aspire SQL Server hosting integration section.

Client integration

To get started with the .NET Aspire SQL Server client integration, install the 📦 Aspire.Microsoft.Data.SqlClient NuGet package in the client-consuming project, that is, the project for the application that uses the SQL Server client. The SQL Server client integration registers a SqlConnection instance that you can use to interact with SQL Server.

dotnet add package Aspire.Microsoft.Data.SqlClient

Add SQL Server client

In the Program.cs file of your client-consuming project, call the AddSqlServerClient extension method on any IHostApplicationBuilder to register a SqlConnection for use via the dependency injection container. The method takes a connection name parameter.

builder.AddSqlServerClient(connectionName: "database");

Tip

The connectionName parameter must match the name used when adding the SQL Server database resource in the app host project. In other words, when you call AddDatabase and provide a name of database that same name should be used when calling AddSqlServerClient. For more information, see Add SQL Server resource and database resource.

You can then retrieve the SqlConnection instance using dependency injection. For example, to retrieve the connection from an example service:

public class ExampleService(SqlConnection connection)
{
    // Use connection...
}

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

Add keyed SQL Server client

There might be situations where you want to register multiple SqlConnection instances with different connection names. To register keyed SQL Server clients, call the AddKeyedSqlServerClient method:

builder.AddKeyedSqlServerClient(name: "mainDb");
builder.AddKeyedSqlServerClient(name: "loggingDb");

Important

When using keyed services, it's expected that your SQL Server resource configured two named databases, one for the mainDb and one for the loggingDb.

Then you can retrieve the SqlConnection instances using dependency injection. For example, to retrieve the connection from an example service:

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

The .NET Aspire SQL Server integration provides multiple options to configure the connection based on the requirements and conventions of your project.

Use a connection string

When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling the AddSqlServerClient method:

builder.AddSqlServerClient(connectionName: "sql");

Then the connection string is retrieved from the ConnectionStrings configuration section:

{
  "ConnectionStrings": {
    "database": "Data Source=myserver;Initial Catalog=master"
  }
}

For more information on how to format this connection string, see the ConnectionString.

Use configuration providers

The .NET Aspire SQL Server integration supports Microsoft.Extensions.Configuration. It loads the MicrosoftDataSqlClientSettings from configuration by using the Aspire:Microsoft:Data:SqlClient key. The following snippet is an example of a appsettings.json file that configures some of the options:

{
  "Aspire": {
    "Microsoft": {
      "Data": {
        "SqlClient": {
          "ConnectionString": "YOUR_CONNECTIONSTRING",
          "DisableHealthChecks": false,
          "DisableMetrics": true
        }
      }
    }
  }
}

For the complete SQL Server client integration JSON schema, see Aspire.Microsoft.Data.SqlClient/ConfigurationSchema.json.

Use inline delegates

Also you can pass the Action<MicrosoftDataSqlClientSettings> configureSettings delegate to set up some or all the options inline, for example to disable health checks from code:

builder.AddSqlServerClient(
    "database",
    static settings => settings.DisableHealthChecks = true);

Client integration health checks

By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.

The .NET Aspire SQL Server integration:

  • Adds the health check when MicrosoftDataSqlClientSettings.DisableHealthChecks is false, which attempts to connect to the SQL Server.
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic.

Observability and telemetry

.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.

Logging

The .NET Aspire SQL Server integration currently doesn't enable logging by default due to limitations of the Microsoft.Data.SqlClient.

Tracing

The .NET Aspire SQL Server integration emits the following tracing activities using OpenTelemetry:

  • OpenTelemetry.Instrumentation.SqlClient

Metrics

The .NET Aspire SQL Server integration will emit the following metrics using OpenTelemetry:

  • 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

See also