.NET Aspire PostgreSQL integration
In this article, you learn how to use the .NET Aspire PostgreSQL integration. The Aspire.Npgsql
library is used to register a NpgsqlDataSource in the DI container for connecting to a PostgreSQL database. It also enables corresponding health checks, logging and telemetry.
Get started
To get started with the .NET Aspire PostgreSQL integration, install the Aspire.Npgsql NuGet package in the client-consuming project, i.e., the project for the application that uses the PostgreSQL client.
dotnet add package Aspire.Npgsql
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Example usage
In the Program.cs file of your client-consuming project, call the AddNpgsqlDataSource extension to register an NpgsqlDataSource
for use via the dependency injection container.
builder.AddNpgsqlDataSource("postgresdb");
After adding NpgsqlDataSource
to the builder, you can get the NpgsqlDataSource
instance using dependency injection. For example, to retrieve your context object from service:
public class ExampleService(NpgsqlDataSource dataSource)
{
// Use dataSource...
}
App host usage
To model the PostgreSQL server resource in the app host, install the Aspire.Hosting.PostgreSQL NuGet package in the app host project.
dotnet add package Aspire.Hosting.PostgreSQL
In your app host project, register and consume the PostgreSQL integration using the following methods, such as AddPostgres:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres");
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
When you want to explicitly provide the username and password, you can provide those as parameters. Consider the following alternative example:
var username = builder.AddParameter("username", secret: true);
var password = builder.AddParameter("password", secret: true);
var postgres = builder.AddPostgres("postgres", username, password);
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
For more information, see External parameters.
When adding PostgreSQL resources to the builder
with the AddPostgres
method, you can chain calls to WithPgWeb
to add the sosedoff/pgweb container. This container is a cross-platform client for PostgreSQL databases, that serves a web-based admin dashboard. Consider the following example:
var postgres = builder.AddPostgres("postgres")
.WithPgWeb();
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
All registered PostgresDatabaseResource
instances are used to create a configuration file per instance, and each config is bound to the pgweb container bookmark directory. For more information, see PgWeb docs: Server connection bookmarks.
Azure app host usage
To deploy your PostgreSQL resources to Azure, you need to install the appropriate .NET Aspire hosting package:
dotnet add package Aspire.Hosting.Azure.PostgreSQL
After you've installed this package, you specify that your PostgreSQL resources will be hosted in Azure by calling the PublishAsAzurePostgresFlexibleServer extension method in your app host project:
var builder = DistributedApplication.CreateBuilder(args);
var postgres = builder.AddPostgres("postgres")
.PublishAsAzurePostgresFlexibleServer();
var postgresdb = postgres.AddDatabase("postgresdb");
var exampleProject = builder.AddProject<Projects.ExampleProject>()
.WithReference(postgresdb);
The preceding call to PublishAsAzurePostgresFlexibleServer
configures Postgres Server resource to be deployed as Azure Postgres Flexible Server. For more information, see Azure Postgres Flexible Server.
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 AddNpgsqlDataSource:
builder.AddNpgsqlDataSource("NpgsqlConnection");
And then the connection string will be retrieved from the ConnectionStrings
configuration section:
{
"ConnectionStrings": {
"NpgsqlConnection": "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": {
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}
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",
settings => settings.DisableHealthChecks = true);
Health checks
By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.
- 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