Skip to content

Commit 82ec85c

Browse files
committed
Update example code in documentation.
Use .NET 8.0, C# 12, and MySqlConnector 2.3.0.
1 parent 58a9178 commit 82ec85c

File tree

2 files changed

+165
-285
lines changed

2 files changed

+165
-285
lines changed

docs/content/tutorials/connect-to-mysql.md

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
---
2-
lastmod: 2023-01-21
2+
lastmod: 2023-11-10
33
date: 2019-11-18
44
menu:
55
main:
@@ -49,27 +49,22 @@ If you are using ASP.NET Core, your connection string will usually be stored in
4949

5050
## 3. Configure Service (ASP.NET Core)
5151

52-
### .NET 6.0
53-
5452
If using ASP.NET Core, you will want to register a database connection in `Program.cs`:
5553

54+
**Recommended** Install [MySqlConnector.DependencyInjection](https://www.nuget.org/packages/MySqlConnector.DependencyInjection/) via `dotnet add package MySqlConnector.DependencyInjection`. Then add the following to `Program.cs`:
55+
5656
```csharp
57-
builder.services.AddTransient<MySqlConnection>(_ =>
58-
new MySqlConnection(builder.Configuration.GetConnectionString["Default"]));
57+
builder.Services.AddMySqlDataSource(builder.Configuration.GetConnectionString("Default")!);
5958
```
6059

61-
### .NET 5.0 and earlier
62-
63-
For .NET 5.0 and earlier, register a database connection in `Startup.cs`:
60+
Alternatively, register a transient `MySqlConnection` object explicitly:
6461

6562
```csharp
66-
public void ConfigureServices(IServiceCollection services)
67-
{
68-
// ...
69-
services.AddTransient<MySqlConnection>(_ => new MySqlConnection(Configuration["ConnectionStrings:Default"]));
70-
}
63+
builder.services.AddTransient<MySqlConnection>(_ =>
64+
new MySqlConnection(builder.Configuration.GetConnectionString["Default"]));
7165
```
7266

67+
The advantage of using `AddMySqlDataSource` is that it will automatically integrate with logging, and also register `DbDataSource` and `DbConnection` with the service collection.
7368

7469
## 4. Open and Use the Connection
7570

0 commit comments

Comments
 (0)