MySqlConnector.DependencyInjection 2.4.0

Prefix Reserved
dotnet add package MySqlConnector.DependencyInjection --version 2.4.0                
NuGet\Install-Package MySqlConnector.DependencyInjection -Version 2.4.0                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MySqlConnector.DependencyInjection" Version="2.4.0" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add MySqlConnector.DependencyInjection --version 2.4.0                
#r "nuget: MySqlConnector.DependencyInjection, 2.4.0"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install MySqlConnector.DependencyInjection as a Cake Addin
#addin nuget:?package=MySqlConnector.DependencyInjection&version=2.4.0

// Install MySqlConnector.DependencyInjection as a Cake Tool
#tool nuget:?package=MySqlConnector.DependencyInjection&version=2.4.0                

About

MySqlConnector.DependencyInjection helps set up MySqlConnector in applications that use dependency injection, most notably in ASP.NET. It allows easy configuration of your MySQL connections and registers the appropriate services in your DI container. It also configures logging by integrating MySqlConnector with the ILoggingFactory registered with the service provider.

How to Use

For example, if using the ASP.NET minimal web API, use the following to register MySqlConnector:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMySqlDataSource(builder.Configuration.GetConnectionString("Default"));

This registers a transient MySqlConnection which can get injected into your controllers:

app.MapGet("/", async (MySqlConnection connection) =>
{
    await connection.OpenAsync();
    await using var command = connection.CreateCommand();
    command.CommandText = "SELECT name FROM users LIMIT 1";
    return "Hello World: " + await command.ExecuteScalarAsync();
});

You can use MySqlDataSource directly if you need more than one connection:

app.MapGet("/", async (MySqlDataSource dataSource) =>
{
    await using var connection1 = await dataSource.OpenConnectionAsync();
    await using var connection2 = await dataSource.OpenConnectionAsync();
    // use the two connections...
});

Advanced Usage

The AddMySqlDataSource method also accepts a lambda parameter allowing you to configure aspects of MySqlConnector beyond the connection string.

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMySqlDataSource("Server=server;User ID=test;Password=test;Database=test",
	x => x.UseRemoteCertificateValidationCallback((sender, certificate, chain, sslPolicyErrors) => { /* custom logic */ })
);

Keyed Services

Use the AddKeyedMySqlDataSource method to register a MySqlDataSource as a keyed service. This is useful if you have multiple connection strings or need to connect to multiple databases. If the service key is a string, it will automatically be used as the MySqlDataSource name; to customize this, call the AddKeyedMySqlDataSource(object?, string, Action<MySqlDataSourceBuilder>) overload and call MySqlDataSourceBuilder.UseName.

builder.Services.AddKeyedMySqlDataSource("users", builder.Configuration.GetConnectionString("Users"));
builder.Services.AddKeyedMySqlDataSource("products", builder.Configuration.GetConnectionString("Products"));

app.MapGet("/users/{userId}", async (int userId, [FromKeyedServices("users")] MySqlConnection connection) =>
{
    await connection.OpenAsync();
    await using var command = connection.CreateCommand();
    command.CommandText = "SELECT name FROM users WHERE user_id = @userId LIMIT 1";
    command.Parameters.AddWithValue("@userId", userId);
    return $"Hello, {await command.ExecuteScalarAsync()}";
});

app.MapGet("/products/{productId}", async (int productId, [FromKeyedServices("products")] MySqlConnection connection) =>
{
    await connection.OpenAsync();
    await using var command = connection.CreateCommand();
    command.CommandText = "SELECT name FROM products WHERE product_id = @productId LIMIT 1";
    command.Parameters.AddWithValue("@productId", productId);
    return await command.ExecuteScalarAsync();
});
Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (2)

Showing the top 2 NuGet packages that depend on MySqlConnector.DependencyInjection:

Package Downloads
Aspire.MySqlConnector

A MySQL client that integrates with Aspire, including health checks, metrics, logging, and telemetry.

CodedThought.Core.Data.MySql

The CodedThought.Core.Data.MySql package is a custom database provider for use with MySql Server.

GitHub repositories (4)

Showing the top 4 popular GitHub repositories that depend on MySqlConnector.DependencyInjection:

Repository Stars
Xabaril/AspNetCore.Diagnostics.HealthChecks
Enterprise HealthChecks for ASP.NET Core Diagnostics Package
dotnet/aspire
Tools, templates, and packages to accelerate building observable, production-ready apps
PomeloFoundation/Pomelo.EntityFrameworkCore.MySql
Entity Framework Core provider for MySQL and MariaDB built on top of MySqlConnector
dotnet/dotnet
Home of .NET's Virtual Monolithic Repository which includes all the code needed to build the .NET SDK from source
Version Downloads Last updated
2.4.0 966 11/12/2024
2.4.0-beta.2 137 10/20/2024
2.4.0-beta.1 80 10/14/2024
2.3.6 68,801 3/20/2024
2.3.5 24,180 1/20/2024
2.3.1 15,093 11/17/2023
2.3.0 436 11/14/2023