# MySQL Client integration reference

<Image
  src={mysqlIcon}
  alt="MySQL logo"
  width={100}
  height={100}
  class:list={'float-inline-left icon'}
  data-zoom-off
/>

To get started with the Aspire MySQL integrations, follow the [Get started with MySQL integrations](../mysql-get-started/) guide.

This article includes full details about the Aspire MySQL Client integration, which allows you to connect to and interact with MySQL databases from your Aspire consuming projects.

## Installation

To get started with the Aspire MySQL client integration, install the [📦 Aspire.MySqlConnector](https://www.nuget.org/packages/Aspire.MySqlConnector) NuGet package in the client-consuming project, that is, the project for the application that uses the MySQL client. The MySQL client integration registers a `MySqlConnector.MySqlDataSource` instance that you can use to interact with MySQL.

<InstallDotNetPackage packageName="Aspire.MySqlConnector" />

## Add a MySQL data source

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:

```csharp title="C# — Program.cs"
builder.AddMySqlDataSource(connectionName: "mysqldb");
```

<Aside type="tip">
The `connectionName` parameter must match the name used when adding the MySQL database resource in the AppHost project.
</Aside>

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

```csharp title="C# — ExampleService.cs"
public class ExampleService(MySqlDataSource dataSource)
{
    // Use dataSource...
}
```

## Add keyed MySQL data source

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:

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

<Aside type="danger">
When using keyed services, it's expected that your MySQL resource configured two named databases, one for the `mainDb` and one for the `loggingDb`.
</Aside>

Then you can retrieve the `MySqlDataSource` instances using dependency injection:

```csharp title="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](https://learn.microsoft.com/dotnet/core/extensions/dependency-injection#keyed-services).

## Properties of the MySQL resources

When you use the `WithReference` method to pass a MySQL server or database resource from the AppHost project to a consuming client project, several properties are available to use in the consuming project.

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

### MySQL server resource

The MySQL server resource exposes the following connection properties:

| Property Name | Description |
|---------------|-------------|
| `Host` | The hostname or IP address of the MySQL server |
| `Port` | The port number the MySQL server is listening on |
| `Username` | The username for authentication |
| `Password` | The password for authentication |
| `Uri` | The connection URI in mysql:// format, with the format `mysql://{Username}:{Password}@{Host}:{Port}` |
| `JdbcConnectionString` | JDBC-format connection string, with the format `jdbc:mysql://{Host}:{Port}`. User and password credentials are provided as separate `Username` and `Password` properties. |

### MySQL database resource

The MySQL database resource inherits all properties from its parent `MySqlServerResource` and adds:

| Property Name | Description |
|---------------|-------------|
| `Uri` | The connection URI with the database name, with the format `mysql://{Username}:{Password}@{Host}:{Port}/{DatabaseName}` |
| `JdbcConnectionString` | JDBC 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. |
| `DatabaseName` | The name of the database |

## Configuration

The MySQL database integration provides multiple options to configure the 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 `AddMySqlDataSource`:

```csharp title="C# — Program.cs"
builder.AddMySqlDataSource(connectionName: "mysql");
```

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

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

For more information on how to format this connection string, see [MySqlConnector: ConnectionString documentation](https://mysqlconnector.net/connection-options/).

### Use configuration providers

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

```json title="JSON — appsettings.json"
{
  "Aspire": {
    "MySqlConnector": {
      "ConnectionString": "YOUR_CONNECTIONSTRING",
      "DisableHealthChecks": true,
      "DisableTracing": true
    }
  }
}
```

For the complete MySQL client integration JSON schema, see [Aspire.MySqlConnector/ConfigurationSchema.json](https://github.com/dotnet/aspire/blob/main/src/Components/Aspire.MySqlConnector/ConfigurationSchema.json).

### Use inline delegates

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

```csharp title="C# — Program.cs"
builder.AddMySqlDataSource(
    "mysql",
    static settings => settings.DisableHealthChecks = true);
```

## Client integration health checks

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

## Observability and telemetry

Aspire integrations automatically set up Logging, Tracing, and Metrics configurations, which are sometimes known as *the pillars of observability*. 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](#configuration) section.

### Logging

The MySQL integration uses the following log categories:

- `MySqlConnector.ConnectionPool`
- `MySqlConnector.MySqlBulkCopy`
- `MySqlConnector.MySqlCommand`
- `MySqlConnector.MySqlConnection`
- `MySqlConnector.MySqlDataSource`

### Tracing

The MySQL integration emits the following tracing activities using OpenTelemetry:

- `MySqlConnector`

### Metrics

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`