.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

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("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.

dotnet add package Aspire.Hosting.PostgreSQL

In your app host project, register and consume the PostgreSQL component 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.

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 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=postgresdb"
  }
}

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": {
      "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 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