Skip to content

Commit

Permalink
Update example code in documentation.
Browse files Browse the repository at this point in the history
Use .NET 8.0, C# 12, and MySqlConnector 2.3.0.
  • Loading branch information
bgrainger committed Nov 11, 2023
1 parent 58a9178 commit 82ec85c
Show file tree
Hide file tree
Showing 2 changed files with 165 additions and 285 deletions.
21 changes: 8 additions & 13 deletions docs/content/tutorials/connect-to-mysql.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
---
lastmod: 2023-01-21
lastmod: 2023-11-10
date: 2019-11-18
menu:
main:
Expand Down Expand Up @@ -49,27 +49,22 @@ If you are using ASP.NET Core, your connection string will usually be stored in

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

### .NET 6.0

If using ASP.NET Core, you will want to register a database connection in `Program.cs`:

**Recommended** Install [MySqlConnector.DependencyInjection](https://www.nuget.org/packages/MySqlConnector.DependencyInjection/) via `dotnet add package MySqlConnector.DependencyInjection`. Then add the following to `Program.cs`:

```csharp
builder.services.AddTransient<MySqlConnection>(_ =>
new MySqlConnection(builder.Configuration.GetConnectionString["Default"]));
builder.Services.AddMySqlDataSource(builder.Configuration.GetConnectionString("Default")!);
```

### .NET 5.0 and earlier

For .NET 5.0 and earlier, register a database connection in `Startup.cs`:
Alternatively, register a transient `MySqlConnection` object explicitly:

```csharp
public void ConfigureServices(IServiceCollection services)
{
// ...
services.AddTransient<MySqlConnection>(_ => new MySqlConnection(Configuration["ConnectionStrings:Default"]));
}
builder.services.AddTransient<MySqlConnection>(_ =>
new MySqlConnection(builder.Configuration.GetConnectionString["Default"]));
```

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

## 4. Open and Use the Connection

Expand Down
Loading

0 comments on commit 82ec85c

Please sign in to comment.