title | description | ms.date | uid |
---|---|---|---|
.NET Aspire PostgreSQL integration |
Learn how to integrate PostgreSQL with .NET Aspire applications, using both hosting and client integrations. |
11/05/2024 |
database/postgresql-integration |
[!INCLUDE includes-hosting-and-client]
PostgreSQL is a powerful, open source object-relational database system with many years of active development that has earned it a strong reputation for reliability, feature robustness, and performance. The .NET Aspire PostgreSQL integration provides a way to connect to existing PostgreSQL databases, or create new instances from .NET with the docker.io/library/postgres
container image.
[!INCLUDE postgresql-app-host]
The PostgreSQL hosting integration automatically adds a health check for the PostgreSQL server resource. The health check verifies that the PostgreSQL server is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.Npgsql NuGet package.
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
<PackageReference Include="Aspire.Npgsql" Version="*" />
In the :::no-loc text="Program.cs"::: file of your client-consuming project, call the xref:Microsoft.Extensions.Hosting.AspirePostgreSqlNpgsqlExtensions.AddNpgsqlDataSource%2A extension method on any xref:Microsoft.Extensions.Hosting.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.
There might be situations where you want to register multiple NpgsqlDataSource
instances with different connection names. To register keyed Npgsql clients, call the xref:Microsoft.Extensions.Hosting.AspirePostgreSqlNpgsqlExtensions.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.
The .NET Aspire PostgreSQL integration provides multiple configuration approaches and options to meet the requirements and conventions of your project.
When using a connection string from the ConnectionStrings
configuration section, you can provide the name of the connection string when calling the xref:Microsoft.Extensions.Hosting.AspirePostgreSqlNpgsqlExtensions.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.
The .NET Aspire PostgreSQL integration supports xref:Microsoft.Extensions.Configuration?displayProperty=fullName. It loads the xref:Aspire.Npgsql.NpgsqlSettings from :::no-loc text="appsettings.json"::: or other configuration files by using the Aspire:Npgsql
key. Example :::no-loc text="appsettings.json"::: that configures some of the options:
The following example shows an :::no-loc text="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.
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);
[!INCLUDE integration-health-checks]
- 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
[!INCLUDE integration-observability-and-telemetry]
The .NET Aspire PostgreSQL integration uses the following log categories:
Npgsql.Connection
Npgsql.Command
Npgsql.Transaction
Npgsql.Copy
Npgsql.Replication
Npgsql.Exception
The .NET Aspire PostgreSQL integration will emit the following Tracing activities using OpenTelemetry:
Npgsql
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
[!INCLUDE postgresql-flexible-server]
[!INCLUDE azure-postgresql-client]