Pular para o conteúdo

Azure SQL Database integration

Este conteúdo não está disponível em sua língua ainda.

Azure SQL Database logo

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 Aspire Azure SQL Server Hosting integration provides methods to create a new Azure Database server and databases from code in your Aspire AppHost project. In a consuming project, you can use the Aspire SQL Server client integration as you would for any other SQL Server instance.

The Aspire Azure SQL Database hosting integration models the SQL Server as the AzureSqlServerResource type and SQL databases as the AzureSqlDatabaseResource type. To access these types and APIs for expressing them within your AppHost project, install the 📦 Aspire.Hosting.Azure.Sql NuGet package:

Aspire CLI — Adicionar pacote Aspire.Hosting.Azure.Sql
aspire add azure-sql

A CLI Aspire é interativa; escolhe o resultado apropriado quando solicitado:

Aspire CLI — Exemplo de saída
Select an integration to add:
> azure-sql (Aspire.Hosting.Azure.Sql)
> Other results listed as selectable options...

Add Azure SQL server resource and database resource

Section titled “Add Azure SQL server resource and database resource”

In your AppHost 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:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
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.

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:

C# — AppHost.cs
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 resources as existing resources, see Use existing Azure resources.

Run Azure SQL server resource as a container

Section titled “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:

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

The Aspire Azure SQL Database client integration is used to connect to an Azure SQL database using Microsoft.Data.SqlClient. To get started with the Aspire Azure SQL Database client integration, install the 📦 Aspire.Microsoft.Data.SqlClient NuGet package.

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

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

builder.AddSqlServerClient(connectionName: "database");

After adding the SqlConnection, you can retrieve the connection instance using dependency injection:

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

For more information, see:

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

builder.AddKeyedSqlServerClient(name: "primary-db");
builder.AddKeyedSqlServerClient(name: "secondary-db");

Then you can retrieve the connection instances using dependency injection:

public class ExampleService(
[KeyedService("primary-db")] SqlConnection primaryConnection,
[KeyedService("secondary-db")] SqlConnection secondaryConnection)
{
// Use connections...
}

For more information, see Keyed services in .NET.

The Aspire Azure SQL Database library provides multiple options to configure the SQL connection based on the requirements and conventions of your project. A ConnectionString is required.

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

builder.AddSqlServerClient(connectionName: "database");

The connection information is retrieved from the ConnectionStrings configuration section:

{
"ConnectionStrings": {
"database": "Server=myserver;Database=mydb;User Id=myuser;Password=mypassword;Encrypt=True"
}
}

The library supports Microsoft.Extensions.Configuration. It loads settings from configuration using the Aspire:Microsoft:Data:SqlClient key:

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

You can configure settings inline:

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

Aspire integrations automatically set up Logging, Tracing, and Metrics configurations.

The Aspire Azure SQL Database integration uses the following log categories:

  • Microsoft.Data.SqlClient

The Aspire Azure SQL Database integration will emit the following tracing activities using OpenTelemetry:

  • Microsoft.Data.SqlClient

The Aspire Azure SQL Database integration will emit the following metrics using OpenTelemetry:

  • Microsoft.Data.SqlClient
    • db.client.connections.create_time
    • db.client.connections.use_time
    • db.client.connections.wait_time
    • db.client.connections.idle.max
    • db.client.connections.idle.min
    • db.client.connections.max
    • db.client.connections.pending_requests
    • db.client.connections.timeouts
    • db.client.connections.usage
Pergunta & RespondeColaboraComunidadeDiscutirVer