Skip to main content

Overview

The Aspire.Npgsql component registers a NpgsqlDataSource in your dependency injection container for connecting to PostgreSQL databases. It automatically enables health checks, metrics, logging, and distributed tracing.

Installation

Install the component using the .NET CLI:
dotnet add package Aspire.Npgsql

Usage

Register the component

In your service’s Program.cs file, call the AddNpgsqlDataSource extension method:
builder.AddNpgsqlDataSource("postgresdb");

Inject and use the data source

Retrieve the NpgsqlDataSource instance using dependency injection:
public class ProductsController : ControllerBase
{
    private readonly NpgsqlDataSource _dataSource;

    public ProductsController(NpgsqlDataSource dataSource)
    {
        _dataSource = dataSource;
    }

    [HttpGet]
    public async Task<IActionResult> GetProducts()
    {
        await using var connection = await _dataSource.OpenConnectionAsync();
        await using var command = connection.CreateCommand();
        command.CommandText = "SELECT id, name, price FROM products";
        
        await using var reader = await command.ExecuteReaderAsync();
        var products = new List<Product>();
        
        while (await reader.ReadAsync())
        {
            products.Add(new Product
            {
                Id = reader.GetInt32(0),
                Name = reader.GetString(1),
                Price = reader.GetDecimal(2)
            });
        }
        
        return Ok(products);
    }
}

Configuration

The component provides multiple configuration options based on your project requirements.

Connection string

Provide a connection string in your appsettings.json:
{
  "ConnectionStrings": {
    "postgresdb": "Host=myserver;Database=mydb;Username=user;Password=pass"
  }
}
Then register the component using the connection name:
builder.AddNpgsqlDataSource("postgresdb");
For more information on connection string format, see the Npgsql connection string documentation.

Configuration providers

Configure component settings using the Aspire:Npgsql configuration section:
{
  "Aspire": {
    "Npgsql": {
      "DisableHealthChecks": true,
      "DisableTracing": false,
      "DisableMetrics": false
    }
  }
}

Inline configuration

Configure settings directly in code using a delegate:
builder.AddNpgsqlDataSource("postgresdb", settings => 
{
    settings.DisableHealthChecks = true;
    settings.DisableTracing = false;
});

AppHost integration

In your AppHost project, install the PostgreSQL hosting package:
dotnet add package Aspire.Hosting.PostgreSQL
Register a PostgreSQL server and database in your AppHost’s Program.cs:
var postgres = builder.AddPostgres("pg")
                      .AddDatabase("postgresdb");

var myService = builder.AddProject<Projects.MyService>()
                       .WithReference(postgres);
The WithReference method automatically configures the connection string in your service. Consume it in your service’s Program.cs:
builder.AddNpgsqlDataSource("postgresdb");
The connection name passed to WithReference must match the name used in AddNpgsqlDataSource.

Configuration options

The following settings are available:
SettingDescriptionDefault
DisableHealthChecksDisable automatic health check registrationfalse
DisableTracingDisable OpenTelemetry tracingfalse
DisableMetricsDisable OpenTelemetry metricsfalse
DisableLoggingDisable loggingfalse

Health checks

The component automatically registers a health check that verifies the database connection. The health check:
  • Opens a connection to the database
  • Executes a simple query to verify connectivity
  • Reports the status in the /health endpoint
You can disable health checks by setting DisableHealthChecks to true.

Observability

Logging

The component integrates with .NET logging to provide:
  • Connection pool events
  • Command execution information
  • Error details

Metrics

The following metrics are collected:
  • Active connections
  • Connection pool statistics
  • Command execution duration
  • Query count

Tracing

Distributed tracing captures:
  • Database operations
  • Query execution time
  • Connection pool activity
Traces appear in the Aspire dashboard and integrate with OpenTelemetry collectors.

Best practices

NpgsqlDataSource includes built-in connection pooling. Reuse the same data source instance throughout your application instead of creating new connections for each operation.
Always use await using when working with connections and commands to ensure proper disposal:
await using var connection = await _dataSource.OpenConnectionAsync();
await using var command = connection.CreateCommand();
Protect against SQL injection by using parameterized queries:
command.CommandText = "SELECT * FROM products WHERE id = @id";
command.Parameters.AddWithValue("@id", productId);
Set command timeouts based on your expected query execution times:
command.CommandTimeout = 30; // 30 seconds

Additional resources

SQL Server

Connect to SQL Server databases

MongoDB

Work with MongoDB databases

Redis

Add caching with Redis

PostgreSQL Hosting

Learn about the PostgreSQL hosting integration

Build docs developers (and LLMs) love