.NET Aspire Pomelo MySQL Entity Framework Core integration
Includes: Hosting integration and Client integration
MySQL is an open-source Relational Database Management System (RDBMS) that uses Structured Query Language (SQL) to manage and manipulate data. It's employed in a many different environments, from small projects to large-scale enterprise systems and it's a popular choice to host data that underpins microservices in a cloud-native application. The .NET Aspire Pomelo MySQL Entity Framework Core integration enables you to connect to existing MySQL databases or create new instances from .NET with the mysql
container image.
Hosting integration
The MySQL hosting integration models the server as the MySqlServerResource type and the database as the MySqlDatabaseResource type. To access these types and APIs, add the 📦 Aspire.Hosting.MySql NuGet package in the app host project.
dotnet add package Aspire.Hosting.MySql
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Add MySQL server resource and database resource
In your app host project, call AddMySql to add and return a MySQL resource builder. Chain a call to the returned resource builder to AddDatabase, to add a MySQL database resource.
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithLifetime(ContainerLifetime.Persistent);
var mysqldb = mysql.AddDatabase("mysqldb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);
// After adding all resources, run the app...
Note
The SQL Server container is slow to start, so it's best to use a persistent lifetime to avoid unnecessary restarts. For more information, see Container resource lifetime.
When .NET Aspire adds a container image to the app host, as shown in the preceding example with the mysql
image, it creates a new MySQL instance on your local machine. A reference to your MySQL resource builder (the mysql
variable) is used to add a database. The database is named mysqldb
and then added to the ExampleProject
. The MySQL resource includes default credentials with a username
of root
and a random password
generated using the CreateDefaultPasswordParameter method.
When the app host runs, the password is stored in the app host's secret store. It's added to the Parameters
section, for example:
{
"Parameters:mysql-password": "<THE_GENERATED_PASSWORD>"
}
The name of the parameter is mysql-password
, but really it's just formatting the resource name with a -password
suffix. For more information, see Safe storage of app secrets in development in ASP.NET Core and Add MySQL resource with parameters.
The WithReference method configures a connection in the ExampleProject
named mysqldb
.
Tip
If you'd rather connect to an existing MySQL server, call AddConnectionString instead. For more information, see Reference existing resources.
Add a MySQL resource with a data volume
To add a data volume to the SQL Server resource, call the WithDataVolume method on the SQL Server resource:
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithDataVolume();
var mysqldb = mysql.AddDatabase("mysqldb");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);
// After adding all resources, run the app...
The data volume is used to persist the MySQL server data outside the lifecycle of its container. The data volume is mounted at the /var/lib/mysql
path in the SQL Server container and when a name
parameter isn't provided, the name is generated at random. For more information on data volumes and details on why they're preferred over bind mounts, see Docker docs: Volumes.
Warning
The password is stored in the data volume. When using a data volume and if the password changes, it will not work until you delete the volume.
Add a MySQL resource with a data bind mount
To add a data bind mount to the MySQL resource, call the WithDataBindMount method:
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithDataBindMount(source: @"C:\MySql\Data");
var db = sql.AddDatabase("mysqldb");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);
// After adding all resources, run the app...
Important
Data bind mounts have limited functionality compared to volumes, which offer better performance, portability, and security, making them more suitable for production environments. However, bind mounts allow direct access and modification of files on the host system, ideal for development and testing where real-time changes are needed.
Data bind mounts rely on the host machine's filesystem to persist the MySQL data across container restarts. The data bind mount is mounted at the C:\MySql\Data
on Windows (or /MySql/Data
on Unix) path on the host machine in the MySQL container. For more information on data bind mounts, see Docker docs: Bind mounts.
Add MySQL resource with parameters
When you want to provide a root MySQL password explicitly, you can pass it as a parameter. Consider the following alternative example:
var password = builder.AddParameter("password", secret: true);
var mysql = builder.AddMySql("mysql", password)
.WithLifetime(ContainerLifetime.Persistent);
var mysqldb = mysql.AddDatabase("mysqldb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);
For more information, see External parameters.
Add a PhpMyAdmin resource
phpMyAdmin is a popular web-based administration tool for MySQL. You can use it to browse and modify MySQL objects such as databases, tables, views, and indexes. To use phpMyAdmin within your .NET Aspire solution, call the WithPhpMyAdmin method. This method adds a new container resource to the solution that hosts phpMyAdmin and connects it to the MySQL container:
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithPhpMyAdmin();
var db = sql.AddDatabase("mysqldb");
builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);
// After adding all resources, run the app...
When you run the solution, the .NET Aspire dashboard displays the phpMyAdmin resources with an endpoint. Select the link to the endpoint to view phpMyAdmin in a new browser tab.
Hosting integration health checks
The MySQL hosting integration automatically adds a health check for the MySQL resource. The health check verifies that the MySQL server is running and that a connection can be established to it.
The hosting integration relies on the 📦 AspNetCore.HealthChecks.MySql NuGet package.
Client integration
To get started with the .NET Aspire Pomelo MySQL Entity Framework integration, install the 📦 Aspire.Pomelo.EntityFrameworkCore.MySql NuGet package in the client-consuming project, that is, the project for the application that uses the MySQL Entity Framework Core client.
dotnet add package Aspire.Pomelo.EntityFrameworkCore.MySql
For more information, see dotnet add package or Manage package dependencies in .NET applications.
Add a MySQL database context
In the Program.cs file of your client-consuming project, call the AddMySqlDbContext extension method on any IHostApplicationBuilder to register a DbContext for use through the dependency injection container. The method takes a connection name parameter.
builder.AddMySqlDbContext<ExampleDbContext>(connectionName: "mysqldb");
Tip
The connectionName
parameter must match the name used when adding the SQL Server database resource in the app host project. In other words, when you call AddDatabase
and provide a name of mysqldb
that same name should be used when calling AddMySqlDbContext
. For more information, see Add MySQL server resource and database resource.
To retrieve ExampleDbContext
object from a service:
public class ExampleService(ExampleDbContext context)
{
// Use context...
}
For more information on dependency injection, see .NET dependency injection.
Add a MySQL database context with enrichment
To enrich the DbContext
with additional services, such as automatic retries, health checks, logging and telemetry, call the EnrichMySqlDbContext method:
builder.EnrichMySqlDbContext<ExampleDbContext>(
connectionName: "mysqldb",
configureSettings: settings =>
{
settings.DisableRetry = false;
settings.CommandTimeout = 30 // seconds
});
The settings
parameter is an instance of the PomeloEntityFrameworkCoreMySqlSettings class.
Configuration
The .NET Aspire Pomelo MySQL Entity Framework Core integration provides multiple options to configure the database connection based on 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 builder.AddMySqlDatabaseDbContext<TContext>()
:
builder.AddMySqlDatabaseDbContext<MyDbContext>("mysql");
And then the connection string will be retrieved from the ConnectionStrings
configuration section:
{
"ConnectionStrings": {
"mysql": "Server=mysql;Database=mysqldb"
}
}
The EnrichMySqlDbContext
won't make use of the ConnectionStrings
configuration section since it expects a DbContext
to be registered at the point it's called.
For more information, see the MySqlConnector: ConnectionString documentation.
Use configuration providers
The .NET Aspire Pomelo MySQL Entity Framework Core integration supports Microsoft.Extensions.Configuration. It loads the PomeloEntityFrameworkCoreMySqlSettings from configuration files such as appsettings.json by using the Aspire:Pomelo:EntityFrameworkCore:MySql
key.
The following example shows an appsettings.json that configures some of the available options:
{
"Aspire": {
"Pomelo": {
"EntityFrameworkCore": {
"MySql": {
"ConnectionString": "YOUR_CONNECTIONSTRING",
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}
}
}
For the complete MySQL integration JSON schema, see Aspire.Pomelo.EntityFrameworkCore.MySql/ConfigurationSchema.json.
Use inline delegates
You can also pass the Action<PomeloEntityFrameworkCoreMySqlSettings>
delegate to set up some or all the options inline, for example to disable health checks from code:
builder.AddMySqlDbContext<MyDbContext>(
"mysqldb",
static settings => settings.DisableHealthChecks = true);
or
builder.EnrichMySqlDbContext<MyDbContext>(
static settings => settings.DisableHealthChecks = true);
Health checks
By default, .NET Aspire integrations enable health checks for all services. For more information, see .NET Aspire integrations overview.
The .NET Aspire Pomelo MySQL Entity Framework Core integration:
- Adds the health check when PomeloEntityFrameworkCoreMySqlSettings.DisableHealthChecks is
false
, which calls EF Core's CanConnectAsync method. - 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 integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as the pillars of observability. For more information about integration observability and telemetry, see .NET Aspire integrations overview. Depending on the backing service, some integrations may only support some of these features. For example, some integrations 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 Pomelo MySQL Entity Framework Core integration 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.Migrations
Microsoft.EntityFrameworkCore.Model
Microsoft.EntityFrameworkCore.Model.Validation
Microsoft.EntityFrameworkCore.Query
Microsoft.EntityFrameworkCore.Update
Tracing
The .NET Aspire Pomelo MySQL Entity Framework Core integration will emit the following tracing activities using OpenTelemetry:
MySqlConnector
Metrics
The .NET Aspire Pomelo MySQL Entity Framework Core integration currently supports the following metrics:
- MySqlConnector:
db.client.connections.create_time
db.client.connections.use_time
db.client.connections.wait_time
db.client.connections.idle.max
db.client.connections.idle.min
db.client.connections.max
db.client.connections.pending_requests
db.client.connections.timeouts
db.client.connections.usage
See also
.NET Aspire