Pular para o conteúdo
Docs Try Aspire
Docs Try

Connect to Azure Database for PostgreSQL

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

Azure Database for PostgreSQL logo

This page describes how consuming apps connect to an Azure Database for PostgreSQL resource that’s already modeled in your AppHost. For the AppHost API surface — adding a flexible server, databases, run-as-container for local dev, password authentication, and more — see Azure PostgreSQL Hosting integration.

When you reference an Azure PostgreSQL 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 PostgreSQL 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 postgresdb becomes POSTGRESDB_URI.

The flexible server resource exposes the following connection properties:

Property NameDescription
HostThe fully qualified domain name of the Azure PostgreSQL flexible server
PortThe port number (fixed at 5432 for Azure Flexible Server)
UriThe connection URI, with the format postgresql://{Host} (Entra ID) or postgresql://{Username}:{Password}@{Host} (password auth)
JdbcConnectionStringJDBC-format connection string, with the format jdbc:postgresql://{Host}?sslmode=require&authenticationPluginClassName=com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin
UsernamePresent when password authentication is enabled; the administrator username
PasswordPresent when password authentication is enabled; the administrator password

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

Property NameDescription
DatabaseNameThe name of the database
UriThe database-specific connection URI, with the format postgresql://{Host}/{DatabaseName} (Entra ID) or postgresql://{Username}:{Password}@{Host}/{DatabaseName} (password auth)
JdbcConnectionStringJDBC connection string with the database name

Example environment variables when you reference a database resource named postgresdb:

POSTGRESDB_HOST=myserver.postgres.database.azure.com
POSTGRESDB_PORT=5432
POSTGRESDB_URI=postgresql://myserver.postgres.database.azure.com/postgresdb
POSTGRESDB_JDBCCONNECTIONSTRING=jdbc:postgresql://myserver.postgres.database.azure.com/postgresdb?sslmode=require&authenticationPluginClassName=...
POSTGRESDB_DATABASENAME=postgresdb

When password authentication is enabled, additional variables are also available:

POSTGRESDB_USERNAME=adminuser
POSTGRESDB_PASSWORD=p%40ssw0rd1

Pick the language your consuming app is written in. Each example assumes your AppHost adds an Azure PostgreSQL database resource named postgresdb and references it from the consuming app.

For C# apps, the recommended approach is the Aspire PostgreSQL client integration. It registers an NpgsqlDataSource 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.Npgsql NuGet package in the client-consuming project:

.NET CLI — Add Aspire.Npgsql package
dotnet add package Aspire.Npgsql

In Program.cs, call AddNpgsqlDataSource on your IHostApplicationBuilder to register an NpgsqlDataSource:

C# — Program.cs
builder.AddNpgsqlDataSource(connectionName: "postgresdb");

Resolve the data source through dependency injection:

C# — ExampleService.cs
public class ExampleService(NpgsqlDataSource dataSource)
{
// Use dataSource...
}

To register multiple NpgsqlDataSource instances with different connection names, use AddKeyedNpgsqlDataSource:

C# — Program.cs
builder.AddKeyedNpgsqlDataSource(name: "catalogdb");
builder.AddKeyedNpgsqlDataSource(name: "ordersdb");

Then resolve each instance by key:

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("catalogdb")] NpgsqlDataSource catalogDataSource,
[FromKeyedServices("ordersdb")] NpgsqlDataSource ordersDataSource)
{
// Use data sources...
}

The Aspire PostgreSQL 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 AddNpgsqlDataSource:

C# — Program.cs
builder.AddNpgsqlDataSource("postgresdb");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"postgresdb": "Host=myserver.postgres.database.azure.com;Database=postgresdb"
}
}

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads NpgsqlSettings from appsettings.json (or any other configuration source) by using the Aspire:Npgsql key:

JSON — appsettings.json
{
"Aspire": {
"Npgsql": {
"ConnectionString": "Host=myserver.postgres.database.azure.com;Database=postgresdb",
"DisableHealthChecks": false,
"DisableTracing": false,
"DisableMetrics": false
}
}
}

Inline delegates. Pass an Action<NpgsqlSettings> to configure settings inline, for example to disable health checks:

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

Aspire client integrations enable health checks by default. The PostgreSQL client integration adds:

  • The NpgSqlHealthCheck, which verifies that commands can be successfully executed against the underlying PostgreSQL database.
  • Integration with the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

The Aspire PostgreSQL client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

  • Npgsql.Connection
  • Npgsql.Command
  • Npgsql.Transaction
  • Npgsql.Copy
  • Npgsql.Replication
  • Npgsql.Exception

Tracing activities:

  • Npgsql

Metrics:

  • ec_Npgsql_bytes_written_per_second
  • ec_Npgsql_bytes_read_per_second
  • ec_Npgsql_commands_per_second
  • ec_Npgsql_total_commands
  • ec_Npgsql_current_commands
  • ec_Npgsql_failed_commands
  • ec_Npgsql_prepared_commands_ratio
  • ec_Npgsql_connection_pools
  • ec_Npgsql_multiplexing_average_commands_per_batch
  • ec_Npgsql_multiplexing_average_write_time_per_batch

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

Use the Azure Npgsql integration for Entra ID

Section titled “Use the Azure Npgsql integration for Entra ID”

When your app targets Azure and you want to use Entra ID (managed identity) authentication — the default for Azure Database for PostgreSQL — install 📦 Aspire.Azure.Npgsql instead and call AddAzureNpgsqlDataSource:

.NET CLI — Add Aspire.Azure.Npgsql package
dotnet add package Aspire.Azure.Npgsql
C# — Program.cs
builder.AddAzureNpgsqlDataSource(connectionName: "postgresdb");

This registers an NpgsqlDataSource with an Entra token provider attached, so no password is required in your configuration. For keyed registrations, use AddKeyedAzureNpgsqlDataSource.

For more information, see PostgreSQL Entity Framework Core integrations if you prefer an EF Core abstraction over raw NpgsqlDataSource.

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and pass it to the 📦 Npgsql NuGet package directly:

C# — Program.cs
using Npgsql;
var connectionString = Environment.GetEnvironmentVariable("POSTGRESDB_URI");
await using var dataSource = NpgsqlDataSource.Create(connectionString!);
await using var conn = await dataSource.OpenConnectionAsync();
// Use conn to query the database...