Azure PostgreSQL client integration

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.

Install the NuGet 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.

Add PostgreSQL client

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:

builder.AddAzureNpgsqlDataSource(connectionName: "postgresdb");

Tip

The connectionName parameter must match the name used when adding the PostgreSQL database resource in the AppHost project. For more information, see Add an Azure Database for PostgreSQL resource.

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:

public class ExampleService(NpgsqlDataSource dataSource)
{
    // Use dataSource...
}

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

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.

Azure PostgreSQL flexible server

The Azure PostgreSQL server resource exposes the following connection properties:

Property Name Description
Host The hostname for the PostgreSQL server
Port The PostgreSQL port (fixed at 5432 in Azure Flexible Server)
Uri The connection URI for the server, with the format postgresql://{Username}:{Password}@{Host} (credentials omitted when not applicable)
JdbcConnectionString JDBC-format connection string for the server, with the format jdbc:postgresql://{Host}?sslmode=require&authenticationPluginClassName=com.azure.identity.extensions.jdbc.postgresql.AzurePostgresqlAuthenticationPlugin
Username Present when password authentication is enabled; the configured administrator username
Password Present when password authentication is enabled; the configured administrator password

Azure PostgreSQL database

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

Property Name Description
DatabaseName The name of the database
Uri The database-specific connection URI, with the format postgresql://{Username}:{Password}@{Host}/{DatabaseName} (credentials omitted when not applicable)
JdbcConnectionString JDBC-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

Add keyed Azure Npgsql client

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:

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:

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

For more information, see Keyed services in .NET.

Configuration

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.

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 AddAzureNpgsqlDataSource:

builder.AddAzureNpgsqlDataSource(connectionName: "database");

The connection information is retrieved from the ConnectionStrings configuration section:

{
  "ConnectionStrings": {
    "database": "Host=myserver;Database=mydb;Username=myuser;Password=mypassword"
  }
}

Use configuration providers

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

{
  "Aspire": {
    "Npgsql": {
      "DisableHealthChecks": true,
      "DisableTracing": false
    }
  }
}

Use inline delegates

You can configure settings inline:

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

Observability and telemetry

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

Logging

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

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

Tracing

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

  • Npgsql

Metrics

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