Ir al contenido

Azure PostgreSQL client integration

Esta página aún no está disponible en tu idioma.

Azure Database for PostgreSQL logo

To get started with the Aspire Azure PostgreSQL client integration, install the 📦 Aspire.Azure.Npgsql NuGet package in the client-consuming project, that is, the project for the application that uses the PostgreSQL client. The PostgreSQL client integration registers an NpgsqlDataSource instance that you can use to interact with PostgreSQL.

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

For an introduction to working with the Azure PostgreSQL client integration, see Get started with the Azure PostgreSQL integrations.

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

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

The preceding code snippet demonstrates how to use the AddAzureNpgsqlDataSource method to register an NpgsqlDataSource instance that uses Azure authentication (Microsoft Entra ID). This "postgresdb" connection name corresponds to a connection string configuration value.

After adding NpgsqlDataSource to the builder, you can get the NpgsqlDataSource instance using dependency injection. For example, to retrieve your data source object from an example service define it as a constructor parameter and ensure the ExampleService class is registered with the dependency injection container:

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

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

Properties of the Azure PostgreSQL resources

Section titled “Properties of the Azure PostgreSQL resources”

When you use the WithReference method to pass an Azure PostgreSQL server or database resource from the AppHost project to a consuming client project, several properties are available to use in the consuming project.

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

The Azure PostgreSQL server resource exposes the following connection properties:

Property NameDescription
HostThe hostname for the PostgreSQL server
PortThe PostgreSQL port (fixed at 5432 in Azure Flexible Server)
UriThe connection URI for the server, with the format postgresql://{Username}:{Password}@{Host} (credentials omitted when not applicable)
JdbcConnectionStringJDBC-format connection string for the server, with the format jdbc:postgresql://{Host}?sslmode=require&authenticationPluginClassName=com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin
UsernamePresent when password authentication is enabled; the configured administrator username
PasswordPresent when password authentication is enabled; the configured administrator password

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

Property NameDescription
DatabaseNameThe name of the database
UriThe database-specific connection URI, with the format postgresql://{Username}:{Password}@{Host}/{DatabaseName} (credentials omitted when not applicable)
JdbcConnectionStringJDBC-format connection string for the database, with the format jdbc:postgresql://{Host}/{DatabaseName}?sslmode=require&authenticationPluginClassName=com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin

For example, if you reference a database resource named postgresdb in your AppHost project, the following environment variables will be available in the consuming project:

  • POSTGRESDB_HOST
  • POSTGRESDB_PORT
  • POSTGRESDB_URI
  • POSTGRESDB_JDBCCONNECTIONSTRING
  • POSTGRESDB_DATABASENAME

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

  • POSTGRESDB_USERNAME
  • POSTGRESDB_PASSWORD

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

C# — Program.cs
builder.AddKeyedAzureNpgsqlDataSource(name: "sales_db");
builder.AddKeyedAzureNpgsqlDataSource(name: "inventory_db");

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

C# — ExampleService.cs
public class ExampleService(
[FromKeyedServices("sales_db")] NpgsqlDataSource salesDataSource,
[FromKeyedServices("inventory_db")] NpgsqlDataSource inventoryDataSource)
{
// Use data sources...
}

For more information, see Keyed services in .NET.

The Aspire Azure Database for PostgreSQL library provides multiple options to configure the PostgreSQL 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 AddAzureNpgsqlDataSource:

C# — Program.cs
builder.AddAzureNpgsqlDataSource(connectionName: "database");

The connection information is retrieved from the ConnectionStrings configuration section:

JSON — appsettings.json
{
"ConnectionStrings": {
"database": "Host=myserver;Database=mydb;Username=myuser;Password=mypassword"
}
}

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

JSON — appsettings.json
{
"Aspire": {
"Npgsql": {
"DisableHealthChecks": true,
"DisableTracing": false
}
}
}

You can configure settings inline:

C# — Program.cs
builder.AddAzureNpgsqlDataSource(
"database",
settings => settings.DisableHealthChecks = true);

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

The Aspire Azure Database for PostgreSQL integration uses the following log categories:

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

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

  • Npgsql

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

  • Npgsql
    • 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