.NET Aspire PostgreSQL Entity Framework Core component
In this article, you learn how to use the .NET Aspire PostgreSQL Entity Framework Core component. The Aspire.Npgsql.EntityFrameworkCore.PostgreSQL
library is used to register a DbContext service for connecting to a PostgreSQL database. It also enables corresponding health checks, logging and telemetry.
PostgreSQL is a powerful, open source, object-relational database system. The .NET Aspire PostgreSQL Entity Framework component streamlines essential database context and connection configurations for you by handling the following concerns:
- Registers EntityFrameworkCore in the DI container for connecting to PostgreSQL database.
- Automatically configures the following:
- Connection pooling to efficiently managed HTTP requests and database connections
- Automatic retries to increase app resiliency
- Health checks, logging and telemetry to improve app monitoring and diagnostics
Prerequisites
- Azure subscription: create one for free
- Azure Postgresql Database: learn more about how to create an Azure Database for PostgreSQL.
Get started
To get started with the .NET Aspire PostgreSQL Entity Framework Core component, install the Aspire.Npgsql.EntityFrameworkCore.PostgreSQL NuGet package.
dotnet add package Aspire.Npgsql.EntityFrameworkCore.PostgreSQL
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 AddNpgsqlDbContext extension to register a DbContext for use via the dependency injection container.
builder.AddNpgsqlDbContext<YourDbContext>("postgresdb");
You can then retrieve the YourDbContext
instance using dependency injection. For example, to retrieve the client from a service:
public class ExampleService(YourDbContext context)
{
// Use context...
}
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 myService = builder.AddProject<Projects.MyService>()
.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 Entity Framework Core component provides multiple configuration approaches and options to meet the requirements and conventions of your project.
Use configuration providers
The .NET Aspire PostgreSQL Entity Framework Core component supports Microsoft.Extensions.Configuration. It loads the NpgsqlEntityFrameworkCorePostgreSQLSettings from configuration files such as appsettings.json by using the Aspire:Npgsql:EntityFrameworkCore:PostgreSQL
key. If you have set up your configurations in the Aspire:Npgsql:EntityFrameworkCore:PostgreSQL
section you can just call the method without passing any parameter.
The following example shows an appsettings.json file that configures some of the available options:
{
"Aspire": {
"Npgsql": {
"EntityFrameworkCore": {
"PostgreSQL": {
"ConnectionString": "YOUR_CONNECTIONSTRING",
"DbContextPooling": true,
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}
}
}
Use inline delegates
You can also pass the Action<NpgsqlEntityFrameworkCorePostgreSQLSettings>
delegate to set up some or all the options inline, for example to set the ConnectionString
:
builder.AddNpgsqlDbContext<YourDbContext>(
"db",
static settings => settings.ConnectionString = "YOUR_CONNECTIONSTRING");
Configure multiple DBContext classes
If you want to register more than one DbContext with different configuration, you can use $"Aspire:Npgsql:EntityFrameworkCore:PostgreSQL:{typeof(TContext).Name}"
configuration section name. The json configuration would look like:
{
"Aspire": {
"Npgsql": {
"EntityFrameworkCore": {
"PostgreSQL": {
"ConnectionString": "YOUR_CONNECTIONSTRING",
"DbContextPooling": true,
"DisableHealthChecks": true,
"DisableTracing": true,
"AnotherDbContext": {
"ConnectionString": "AnotherDbContext_CONNECTIONSTRING",
"DisableTracing": false
}
}
}
}
}
}
Then calling the AddNpgsqlDbContext method with AnotherDbContext
type parameter would load the settings from Aspire:Npgsql:EntityFrameworkCore:PostgreSQL:AnotherDbContext
section.
builder.AddNpgsqlDbContext<AnotherDbContext>();
Configuration options
Here are the configurable options with corresponding default values:
Name | Description |
---|---|
ConnectionString |
The connection string of the SQL Server database to connect to. |
MaxRetryCount |
The maximum number of retry attempts. Default value is 6, set it to 0 to disable the retry mechanism. |
DisableHealthChecks |
A boolean value that indicates whether the database health check is disabled or not. |
DisableTracing |
A boolean value that indicates whether the OpenTelemetry tracing is disabled or not. |
DisableMetrics |
A boolean value that indicates whether the OpenTelemetry metrics are disabled or not. |
Health checks
By default, .NET Aspire components enable health checks for all services. For more information, see .NET Aspire components overview.
By default, the .NET Aspire PostgreSQL Entity Framework Core components handles the following:
- Adds the
DbContextHealthCheck
, which calls EF Core's CanConnectAsync method. The name of the health check is the name of theTContext
type. - 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 Entity Framework Core component uses the following Log categories:
Microsoft.EntityFrameworkCore.ChangeTracking
Microsoft.EntityFrameworkCore.Database.Command
Microsoft.EntityFrameworkCore.Database.Connection
Microsoft.EntityFrameworkCore.Database.Transaction
Microsoft.EntityFrameworkCore.Infrastructure
Microsoft.EntityFrameworkCore.Infrastructure
Microsoft.EntityFrameworkCore.Migrations
Microsoft.EntityFrameworkCore.Model
Microsoft.EntityFrameworkCore.Model.Validation
Microsoft.EntityFrameworkCore.Query
Microsoft.EntityFrameworkCore.Update
Tracing
The .NET Aspire PostgreSQL Entity Framework Core component will emit the following Tracing activities using OpenTelemetry:
- "Npgsql"
Metrics
The .NET Aspire PostgreSQL Entity Framework Core component will emit the following metrics using OpenTelemetry:
Microsoft.EntityFrameworkCore:
- ec_Microsoft_EntityFrameworkCore_active_db_contexts
- ec_Microsoft_EntityFrameworkCore_total_queries
- ec_Microsoft_EntityFrameworkCore_queries_per_second
- ec_Microsoft_EntityFrameworkCore_total_save_changes
- ec_Microsoft_EntityFrameworkCore_save_changes_per_second
- ec_Microsoft_EntityFrameworkCore_compiled_query_cache_hit_rate
- ec_Microsoft_Entity_total_execution_strategy_operation_failures
- ec_Microsoft_E_execution_strategy_operation_failures_per_second
- ec_Microsoft_EntityFramew_total_optimistic_concurrency_failures
- ec_Microsoft_EntityF_optimistic_concurrency_failures_per_second
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
.NET Aspire
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for