.NET Aspire PostgreSQL component

In this article, you learn how to use the .NET Aspire PostgreSQL component. 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 component, install the Aspire.Npgsql NuGet package.

dotnet add package Aspire.Npgsql --prerelease

For more information, see dotnet add package or Manage package dependencies in .NET applications.

Example usage

In the Program.cs file of your component-consuming project, call the AddNpgsqlDataSource extension to register an NpgsqlDataSource for use via the dependency injection container.

builder.AddNpgsqlDataSource("db");

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

In your app host project, register and consume the PostgreSQL component using the following methods, such as AddPostgres:

var postgresdb = builder.AddPostgres("pg")
                        .AddDatabase("postgresdb");

var exampleProject = builder.AddProject<Projects.ExampleProject>()
                            .WithReference(postgresdb);

The WithReference method configures a connection in the ExampleProject named postgresdb. In the Program.cs file of the ExampleService project, the database connection can be consumed using:

builder.AddNpgsqlDataSource("postgresdb");

Configuration

The .NET Aspire PostgreSQL component 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=test"
  }
}

Use configuration providers

The .NET Aspire PostgreSQL component 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": {
      "HealthChecks": false,
      "Tracing": false
    }
  }
}

Use inline delegates

You can also pass the Action<NpgsqlSettings> configureSettings delegate to set up some or all the options inline, for example to set the ConnectionString:

builder.AddNpgsqlDataSource(
    "postgresdb",
     settings => settings.HealthChecks = false);

Health checks

By default, .NET Aspire components enable health checks for all services. For more information, see .NET Aspire components 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 components automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about component observability and telemetry, see .NET Aspire components overview. Depending on the backing service, some components may only support some of these features. For example, some components 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 component uses the following Log categories:

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

Tracing

The .NET Aspire PostgreSQL component will emit the following Tracing activities using OpenTelemetry:

  • "Npgsql"

Metrics

The .NET Aspire PostgreSQL component 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

See also