Provides extension methods and resource definitions for a .NET Aspire AppHost to configure Azure Database for PostgreSQL.
- Azure subscription - create one for free
In your AppHost project, install the .NET Aspire Azure PostgreSQL Hosting library with NuGet:
dotnet add package Aspire.Hosting.Azure.PostgreSQL
Adding Azure resources to the .NET Aspire application model will automatically enable development-time provisioning for Azure resources so that you don't need to configure them manually. Provisioning requires a number of settings to be available via .NET configuration. Set these values in user secrets in order to allow resources to be configured automatically.
{ "Azure": { "SubscriptionId": "<your subscription id>", "ResourceGroupPrefix": "<prefix for the resource group>", "Location": "<azure location>" } }
NOTE: Developers must have Owner access to the target subscription so that role assignments can be configured for the provisioned resources.
Then, in the Program.cs file of AppHost
, register a Postgres database and consume the connection using the following methods:
varpostgresdb=builder.AddAzurePostgresFlexibleServer("pg").AddDatabase("postgresdb");varmyService=builder.AddProject<Projects.MyService>().WithReference(postgresdb);
The WithReference
method configures a connection in the MyService
project named postgresdb
. By default, AddAzurePostgresFlexibleServer
configures Microsoft Entra ID authentication. This requires changes to applications that need to connect to these resources. In the Program.cs file of MyService
, the database connection can be consumed using the client library Aspire.Azure.Npgsql or Aspire.Azure.Npgsql.EntityFrameworkCore.PostgreSQL:
builder.AddAzureNpgsqlDataSource("postgresdb");
- https://www.npgsql.org/doc/basic-usage.html
- https://github.com/dotnet/aspire/tree/main/src/Components/README.md
https://github.com/dotnet/aspire
*Postgres, PostgreSQL and the Slonik Logo are trademarks or registered trademarks of the PostgreSQL Community Association of Canada, and used with their permission.