Skip to main content

Overview

The Aspire.Microsoft.Data.SqlClient component registers a scoped SqlConnection factory in your dependency injection container for connecting to Azure SQL and SQL Server databases. It automatically enables health checks, logging, and distributed tracing.

Installation

Install the component using the .NET CLI:
dotnet add package Aspire.Microsoft.Data.SqlClient

Usage

Register the component

In your service’s Program.cs file, call the AddSqlServerClient extension method:
builder.AddSqlServerClient("sqldata");

Inject and use the connection

Retrieve the SqlConnection instance using dependency injection:
public class ProductsController : ControllerBase
{
    private readonly SqlConnection _connection;

    public ProductsController(SqlConnection connection)
    {
        _connection = connection;
    }

    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        await _connection.OpenAsync();
        
        using var command = _connection.CreateCommand();
        command.CommandText = "SELECT Id, Name, Price FROM Products";
        
        using var reader = await command.ExecuteReaderAsync();
        var products = new List<Product>();
        
        while (await reader.ReadAsync())
        {
            products.Add(new Product
            {
                Id = reader.GetInt32(0),
                Name = reader.GetString(1),
                Price = reader.GetDecimal(2)
            });
        }
        
        return Ok(products);
    }
}
The SqlConnection is registered as scoped, meaning a new connection is created per request in web applications.

Configuration

The component provides multiple configuration options based on your project requirements.

Connection string

Provide a connection string in your appsettings.json:
{
  "ConnectionStrings": {
    "sqldata": "Server=myserver;Database=mydb;User Id=user;Password=pass"
  }
}
Then register the component using the connection name:
builder.AddSqlServerClient("sqldata");
For more information on connection string format, see the SQL Server connection string documentation.

Configuration providers

Configure component settings using the Aspire:Microsoft:Data:SqlClient configuration section:
{
  "Aspire": {
    "Microsoft": {
      "Data": {
        "SqlClient": {
          "DisableHealthChecks": false,
          "DisableTracing": false
        }
      }
    }
  }
}

Inline configuration

Configure settings directly in code using a delegate:
builder.AddSqlServerClient("sqldata", settings => 
{
    settings.DisableHealthChecks = true;
});

AppHost integration

In your AppHost project, install the SQL Server hosting package:
dotnet add package Aspire.Hosting.SqlServer
Register a SQL Server instance and database in your AppHost’s Program.cs:
var sql = builder.AddSqlServer("sql")
                 .AddDatabase("sqldata");

var myService = builder.AddProject<Projects.MyService>()
                       .WithReference(sql);
The WithReference method automatically configures the connection string in your service. Consume it in your service’s Program.cs:
builder.AddSqlServerClient("sqldata");
The connection name passed to WithReference must match the name used in AddSqlServerClient.

Configuration options

The following settings are available:
SettingDescriptionDefault
DisableHealthChecksDisable automatic health check registrationfalse
DisableTracingDisable OpenTelemetry tracingfalse

Health checks

The component automatically registers a health check that verifies the database connection. The health check:
  • Opens a connection to the database
  • Executes a simple query to verify connectivity
  • Reports the status in the /health endpoint
You can disable health checks by setting DisableHealthChecks to true.

Observability

Logging

The component integrates with .NET logging to provide:
  • Connection events
  • Command execution information
  • Error details

Tracing

Distributed tracing captures:
  • Database operations
  • Query execution time
  • Connection activity
Traces appear in the Aspire dashboard and integrate with OpenTelemetry collectors.

Best practices

Always inject SqlConnection through the constructor rather than creating connections manually. This ensures proper lifecycle management and integration with Aspire’s observability features.
Protect against SQL injection by using parameterized queries:
command.CommandText = "SELECT * FROM Products WHERE Id = @id";
command.Parameters.AddWithValue("@id", productId);
Check the connection state before executing commands:
if (_connection.State != ConnectionState.Open)
{
    await _connection.OpenAsync();
}
Always use async methods for database operations to avoid blocking threads:
await connection.OpenAsync();
await command.ExecuteReaderAsync();
Use using statements to ensure proper disposal of commands and readers:
using var command = connection.CreateCommand();
using var reader = await command.ExecuteReaderAsync();

Common scenarios

Azure SQL with managed identity

For Azure SQL databases, use managed identity for authentication:
{
  "ConnectionStrings": {
    "sqldata": "Server=myserver.database.windows.net;Database=mydb;Authentication=Active Directory Default"
  }
}

Connection resilience

Add connection resiliency for production environments:
{
  "ConnectionStrings": {
    "sqldata": "Server=myserver;Database=mydb;ConnectRetryCount=3;ConnectRetryInterval=10"
  }
}

Additional resources

PostgreSQL

Connect to PostgreSQL databases

MongoDB

Work with MongoDB databases

Azure Cosmos DB

Connect to Azure Cosmos DB

SQL Server Hosting

Learn about the SQL Server hosting integration

Build docs developers (and LLMs) love