Skip to content

MySQL integration

MySQL logo

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 Aspire MySQL database integration enables you to connect to existing MySQL databases or create new instances from .NET with the mysql container image.

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 your AppHost project:

Aspire CLI — Add Aspire.Hosting.MySql package
aspire add mysql

The Aspire CLI is interactive, be sure to select the appropriate search result when prompted:

Aspire CLI — Example output prompt
Select an integration to add:
> mysql (Aspire.Hosting.MySql)
> Other results listed as selectable options...

Add MySQL server resource and database resource

Section titled “Add MySQL server resource and database resource”

In your AppHost 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:

C# — AppHost.cs
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);

When Aspire adds a container image to the AppHost, it creates a new MySQL instance on your local machine. The MySQL resource includes default credentials with a username of root and a random password generated using the default password parameter.

When the AppHost runs, the password is stored in the AppHost’s secret store in the Parameters section:

{
"Parameters:mysql-password": "<THE_GENERATED_PASSWORD>"
}

The WithReference method configures a connection in the ExampleProject named mysqldb.

To add a data volume to the MySQL resource, call the WithDataVolume method on the MySQL resource:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithDataVolume();
var mysqldb = mysql.AddDatabase("mysqldb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);

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 MySQL 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.

Add a MySQL resource with a data bind mount

Section titled “Add a MySQL resource with a data bind mount”

To add a data bind mount to the MySQL resource, call the WithDataBindMount method:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithDataBindMount(source: @"C:\MySql\Data");
var mysqldb = mysql.AddDatabase("mysqldb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);

Data bind mounts rely on the host machine’s filesystem to persist the MySQL data across container restarts. For more information on data bind mounts, see Docker docs: Bind mounts.

When you want to provide a root MySQL password explicitly, you can pass it as a parameter:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
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.

phpMyAdmin is a popular web-based administration tool for MySQL. To use phpMyAdmin within your Aspire solution, call the WithPhpMyAdmin method. This method adds a new container resource that hosts phpMyAdmin and connects it to the MySQL container:

C# — AppHost.cs
var builder = DistributedApplication.CreateBuilder(args);
var mysql = builder.AddMySql("mysql")
.WithPhpMyAdmin();
var mysqldb = mysql.AddDatabase("mysqldb");
var myService = builder.AddProject<Projects.ExampleProject>()
.WithReference(mysqldb)
.WaitFor(mysqldb);

When you run the solution, the Aspire dashboard displays the phpMyAdmin resources with an endpoint. Select the link to the endpoint to view phpMyAdmin in a new browser tab.

When you reference a MySQL resource using WithReference, the following connection properties are made available to the consuming project:

The MySQL server resource exposes the following connection properties:

Property NameDescription
HostThe hostname or IP address of the MySQL server
PortThe port number the MySQL server is listening on
UsernameThe username for authentication
PasswordThe password for authentication
UriThe connection URI, with the format mysql://root:{Password}@{Host}:{Port}
JdbcConnectionStringThe JDBC connection string for MySQL, with the format jdbc:mysql://{Host}:{Port}. User and password credentials are provided as separate Username and Password properties.

Example connection strings:

Uri: mysql://root:p%40ssw0rd1@localhost:3306
JdbcConnectionString: jdbc:mysql://localhost:3306

The MySQL database resource combines the server properties above and adds the following connection properties:

Property NameDescription
DatabaseThe MySQL database name
UriThe database-specific URI, with the format mysql://root:{Password}@{Host}:{Port}/{Database}
JdbcConnectionStringThe database-specific JDBC connection string, with the format jdbc:mysql://{Host}:{Port}/{Database}. User and password credentials are provided as separate Username and Password properties.

Example connection strings:

Uri: mysql://root:p%40ssw0rd1@localhost:3306/catalog
JdbcConnectionString: jdbc:mysql://localhost:3306/catalog

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.

To get started with the Aspire MySQL client integration, install the 📦 Aspire.MySqlConnector NuGet package:

.NET CLI — Add Aspire.MySqlConnector package
dotnet add package Aspire.MySqlConnector

The MySQL client integration registers a MySqlConnector.MySqlDataSource instance that you can use to interact with the MySQL server.

In the Program.cs file of your client-consuming project, call the AddMySqlDataSource extension method to register a MySqlDataSource for use via the dependency injection container:

builder.AddMySqlDataSource(connectionName: "mysqldb");

You can then retrieve the MySqlConnector.MySqlDataSource instance using dependency injection:

public class ExampleService(MySqlDataSource dataSource)
{
// Use dataSource...
}

There might be situations where you want to register multiple MySqlDataSource instances with different connection names. To register keyed MySQL data sources, call the AddKeyedMySqlDataSource method:

builder.AddKeyedMySqlDataSource(name: "mainDb");
builder.AddKeyedMySqlDataSource(name: "loggingDb");

Then you can retrieve the MySqlDataSource instances using dependency injection:

public class ExampleService(
[FromKeyedServices("mainDb")] MySqlDataSource mainDataSource,
[FromKeyedServices("loggingDb")] MySqlDataSource loggingDataSource)
{
// Use data sources...
}

For more information on keyed services, see .NET dependency injection: Keyed services.

The MySQL database integration provides multiple options to configure the connection based on the requirements and conventions of your project.

When using a connection string from the ConnectionStrings configuration section, you can provide the name of the connection string when calling AddMySqlDataSource:

builder.AddMySqlDataSource(connectionName: "mysql");

Then the connection string is retrieved from the ConnectionStrings configuration section:

{
"ConnectionStrings": {
"mysql": "Server=mysql;Database=mysqldb"
}
}

For more information on how to format this connection string, see MySqlConnector: ConnectionString documentation.

The MySQL database integration supports Microsoft.Extensions.Configuration. It loads the MySqlConnectorSettings from configuration using the Aspire:MySqlConnector key. Example appsettings.json:

{
"Aspire": {
"MySqlConnector": {
"ConnectionString": "YOUR_CONNECTIONSTRING",
"DisableHealthChecks": true,
"DisableTracing": true
}
}
}

You can pass the Action<MySqlConnectorSettings> delegate to set up some or all the options inline:

builder.AddMySqlDataSource(
"mysql",
static settings => settings.DisableHealthChecks = true);

By default, Aspire integrations enable health checks for all services. The MySQL database integration:

  • Adds the health check when DisableHealthChecks is false, which verifies that a connection can be made and commands can be run against the MySQL database
  • Integrates with the /health HTTP endpoint, which specifies all registered health checks must pass for app to be considered ready to accept traffic

The MySQL integration uses the following log categories:

  • MySqlConnector.ConnectionPool
  • MySqlConnector.MySqlBulkCopy
  • MySqlConnector.MySqlCommand
  • MySqlConnector.MySqlConnection
  • MySqlConnector.MySqlDataSource

The MySQL integration emits the following tracing activities using OpenTelemetry:

  • MySqlConnector

The MySQL integration will emit the following metrics using OpenTelemetry:

  • 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
FAQCollaborateCommunityDiscussWatch