Перейти до вмісту
Docs Try Aspire
Docs Try

Connect to MySQL

Цей контент ще не доступний вашою мовою.

MySQL logo

This page describes how consuming apps connect to a MySQL resource that’s already modeled in your AppHost. For the AppHost API surface — adding a MySQL server, databases, phpMyAdmin, volumes, init files, and more — see MySQL Hosting integration.

When you reference a MySQL resource from your AppHost, Aspire injects the connection information into the consuming app as environment variables. Your app can either read those environment variables directly — the pattern works the same from any language — or, in C#, use the Aspire MySQL client integration for automatic dependency injection, health checks, and telemetry.

Aspire exposes each property as an environment variable named [RESOURCE]_[PROPERTY]. For instance, the Uri property of a resource called mysqldb becomes MYSQLDB_URI.

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 (root by default)
PasswordThe password for authentication
UriThe connection URI in mysql:// format, with the format mysql://{Username}:{Password}@{Host}:{Port}
JdbcConnectionStringJDBC-format connection string, 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 inherits all properties from its parent server resource and adds:

Property NameDescription
UriThe connection URI with the database name, with the format mysql://{Username}:{Password}@{Host}:{Port}/{DatabaseName}
JdbcConnectionStringJDBC connection string with database name, with the format jdbc:mysql://{Host}:{Port}/{DatabaseName}. User and password credentials are provided as separate Username and Password properties.
DatabaseNameThe name of the database

Example connection strings:

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

Pick the language your consuming app is written in. Each example assumes your AppHost adds a MySQL database resource named mysqldb and references it from the consuming app.

For C# apps, the recommended approach is the Aspire MySQL client integration. It registers a MySqlDataSource through dependency injection and adds health checks and telemetry automatically. If you’d rather read environment variables directly, see the Read environment variables section at the end of this tab.

Install the 📦 Aspire.MySqlConnector NuGet package in the client-consuming project:

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

In Program.cs, call AddMySqlDataSource on your IHostApplicationBuilder to register a MySqlDataSource:

C# — Program.cs
builder.AddMySqlDataSource(connectionName: "mysqldb");

Resolve the data source through dependency injection:

C# — ExampleService.cs
public class ExampleService(MySqlDataSource dataSource)
{
// Use dataSource...
}

To register multiple MySqlDataSource instances with different connection names, use AddKeyedMySqlDataSource:

C# — Program.cs
builder.AddKeyedMySqlDataSource(name: "mainDb");
builder.AddKeyedMySqlDataSource(name: "loggingDb");

Then resolve each instance by key:

C# — ExampleService.cs
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 Aspire MySQL client integration offers multiple ways to provide configuration.

Connection strings. When using a connection string from the ConnectionStrings configuration section, pass the connection name to AddMySqlDataSource:

C# — Program.cs
builder.AddMySqlDataSource("mysqldb");

The connection string is resolved from the ConnectionStrings section:

JSON — appsettings.json
{
"ConnectionStrings": {
"mysqldb": "Server=mysql;Database=mysqldb"
}
}

For more information, see MySqlConnector: ConnectionString documentation.

Configuration providers. The client integration supports Microsoft.Extensions.Configuration. It loads MySqlConnectorSettings from appsettings.json (or any other configuration source) by using the Aspire:MySqlConnector key:

JSON — appsettings.json
{
"Aspire": {
"MySqlConnector": {
"ConnectionString": "Server=mysql;Database=mysqldb",
"DisableHealthChecks": false,
"DisableTracing": false,
"DisableMetrics": false
}
}
}

For the complete MySQL client integration JSON schema, see Aspire.MySqlConnector/ConfigurationSchema.json.

Inline delegates. Pass an Action<MySqlConnectorSettings> to configure settings inline, for example to disable health checks:

C# — Program.cs
builder.AddMySqlDataSource(
"mysqldb",
static settings => settings.DisableHealthChecks = true);

Aspire client integrations enable health checks by default. The MySQL client integration adds:

  • A health check that verifies a connection can be made and commands can be executed against the MySQL database.
  • Integration with the /health HTTP endpoint, where all registered health checks must pass before the app is considered ready to accept traffic.

The Aspire MySQL client integration automatically configures logging, tracing, and metrics through OpenTelemetry.

Logging categories:

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

Tracing activities:

  • MySqlConnector

Metrics:

  • 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

Any of these telemetry features can be disabled through the configuration options above.

If you prefer not to use the Aspire client integration, you can read the Aspire-injected connection URI from the environment and connect using the 📦 MySqlConnector NuGet package directly:

C# — Program.cs
using MySqlConnector;
var connectionString = Environment.GetEnvironmentVariable("MYSQLDB_URI");
await using var dataSource = MySqlDataSource.Create(connectionString!);
await using var conn = await dataSource.OpenConnectionAsync();
// Use conn to query the database...