.NET Aspire Azure PostgreSQL integration
Includes:
Hosting integration and
Client integration
Azure Database for PostgreSQL—Flexible Server is a relational database service based on the open-source Postgres database engine. It's a fully managed database-as-a-service that can handle mission-critical workloads with predictable performance, security, high availability, and dynamic scalability. The .NET Aspire Azure PostgreSQL integration provides a way to connect to existing Azure PostgreSQL databases, or create new instances from .NET with the docker.io/library/postgres
container image.
Hosting integration
The .NET Aspire Azure PostgreSQL hosting integration models a PostgreSQL flexible server and database as the AzurePostgresFlexibleServerResource and AzurePostgresFlexibleServerDatabaseResource types. Other types that are inherently available in the hosting integration are represented in the following resources:
To access these types and APIs for expressing them as resources in your app host project, install the 📦 Aspire.Hosting.Azure.PostgreSQL NuGet package:
dotnet add package Aspire.Hosting.Azure.PostgreSQL
For more information, see dotnet add package.
The Azure PostgreSQL hosting integration takes a dependency on the 📦 Aspire.Hosting.PostgreSQL NuGet package, extending it to support Azure. Everything that you can do with the .NET Aspire PostgreSQL integration and .NET Aspire PostgreSQL Entity Framework Core integration you can also do with this integration.
Add Azure PostgreSQL server resource
After you've installed the .NET Aspire Azure PostgreSQL hosting integration, call the AddAzurePostgresFlexibleServer extension method in your app host project:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddAzurePostgresFlexibleServer("postgres");
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
The preceding call to AddAzurePostgresFlexibleServer
configures the PostgresSQL server resource to be deployed as an Azure Postgres Flexible Server.
Important
By default, AddAzurePostgresFlexibleServer
configures Microsoft Entra ID authentication. This requires changes to applications that need to connect to these resources. For more information, see Client integration.
Tip
When you call AddAzurePostgresFlexibleServer, it implicitly calls AddAzureProvisioning—which adds support for generating Azure resources dynamically during app startup. The app must configure the appropriate subscription and location. For more information, see Local provisioning: Configuration.
Client integration
To get started with the .NET Aspire PostgreSQL client integration, install the 📦 Aspire.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.
dotnet add package Aspire.Npgsql
Add Npgsql client
In the Program.cs file of your client-consuming project, call the AddNpgsqlDataSource extension method on any IHostApplicationBuilder to register an NpgsqlDataSource
for use via the dependency injection container. The method takes a connection name parameter.
builder.AddNpgsqlDataSource(connectionName: "postgresdb");
Tip
The connectionName
parameter must match the name used when adding the PostgreSQL server resource in the app host project. For more information, see Add PostgreSQL server resource.
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.
Add keyed 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 AddKeyedNpgsqlDataSource method:
builder.AddKeyedNpgsqlDataSource(name: "chat");
builder.AddKeyedNpgsqlDataSource(name: "queue");
Then you can retrieve the NpgsqlDataSource
instances using dependency injection. For example, to retrieve the connection from an example service:
public class ExampleService(
[FromKeyedServices("chat")] NpgsqlDataSource chatDataSource,
[FromKeyedServices("queue")] NpgsqlDataSource queueDataSource)
{
// Use data sources...
}
For more information on keyed services, see .NET dependency injection: Keyed services.
Configuration
The .NET Aspire PostgreSQL integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.
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 the AddNpgsqlDataSource method:
builder.AddNpgsqlDataSource("postgresdb");
Then the connection string will be retrieved from the ConnectionStrings
configuration section:
{
"ConnectionStrings": {
"postgresdb": "Host=myserver;Database=postgresdb"
}
}
For more information, see the ConnectionString.
Use configuration providers
The .NET Aspire PostgreSQL integration supports Microsoft.Extensions.Configuration. It loads the NpgsqlSettings from appsettings.json or other configuration files by using the Aspire:Npgsql
key. Example appsettings.json that configures some of the options:
The following example shows an appsettings.json file that configures some of the available options:
{
"Aspire": {
"Npgsql": {
"ConnectionString": "Host=myserver;Database=postgresdb",
"DisableHealthChecks": false,
"DisableTracing": true,
"DisableMetrics": false
}
}
}
For the complete PostgreSQL client integration JSON schema, see Aspire.Npgsql/ConfigurationSchema.json.
Use inline delegates
You can also pass the Action<NpgsqlSettings> configureSettings
delegate to set up some or all the options inline, for example to disable health checks:
builder.AddNpgsqlDataSource(
"postgresdb",
static settings => settings.DisableHealthChecks = true);
Client integration health checks
By default, .NET Aspire client integrations have health checks enabled for all services. Similarly, many .NET Aspire hosting integrations also enable health check endpoints. For more information, see:
- Adds the
NpgSqlHealthCheck
, which verifies that commands can be successfully executed against the underlying Postgres database. - Integrates with the
/health
HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic
Observability and telemetry
.NET Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations support logging and tracing, but not metrics. Telemetry features can also be disabled using the techniques presented in the Configuration section.
Logging
The .NET Aspire PostgreSQL integration uses the following log categories:
Npgsql.Connection
Npgsql.Command
Npgsql.Transaction
Npgsql.Copy
Npgsql.Replication
Npgsql.Exception
Tracing
The .NET Aspire PostgreSQL integration will emit the following tracing activities using OpenTelemetry:
Npgsql
Metrics
The .NET Aspire PostgreSQL integration will emit the following metrics using OpenTelemetry:
- Npgsql:
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
Add Azure authenticated Npgsql client
By default, when you call AddAzurePostgresFlexibleServer
in your PostgreSQL hosting integration, it configures 📦 Azure.Identity NuGet package to enable authentication:
dotnet add package Azure.Identity
The PostgreSQL connection can be consumed using the client integration and Azure.Identity:
builder.AddNpgsqlDataSource(
"postgresdb",
configureDataSourceBuilder: (dataSourceBuilder) =>
{
if (!string.IsNullOrEmpty(dataSourceBuilder.ConnectionStringBuilder.Password))
{
return;
}
dataSourceBuilder.UsePeriodicPasswordProvider(async (_, ct) =>
{
var credentials = new DefaultAzureCredential();
var token = await credentials.GetTokenAsync(
new TokenRequestContext([
"https://ossrdbms-aad.database.windows.net/.default"
]), ct);
return token.Token;
},
TimeSpan.FromHours(24),
TimeSpan.FromSeconds(10));
});
The preceding code snippet demonstrates how to use the DefaultAzureCredential class from the Azure.Identity package to authenticate with Microsoft Entra ID and retrieve a token to connect to the PostgreSQL database. The UsePeriodicPasswordProvider method is used to provide the token to the connection string builder.
See also
.NET Aspire