'Why register MysqlConnection as Service?

I'm trying to learn asp.net core 6.0, and I have a website that I'm working on. I needed a mysql connection in my website. I opened google and started searching. I write a code and it works without any problem;

using (var con = new MySqlConnection("server=127.0.0.1;user=dbuser;password=123456;database=gamedata")) {
    con.Open();
    MySqlCommand command = new MySqlCommand("SELECT * FROM userdata WHERE id=7", con);
    var o = command.ExecuteReader();
    if (o.Read()) {
        Console.WriteLine(o["email"]);
    }
}

But in the documentation (not sure it's official). There is a step for registering service. I kept searching and almost every documentation says "do this" without any reason, for example;

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

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

Is it a must or an option, why would I do this? And why my code still works fine without this line?



Solution 1:[1]

This pattern is used for Dependency Injection in ASP.NET Core. Your startup code provides a way (using AddTransient) to create a MySqlConnection whenever one is needed. Your controllers or models can then access a MySqlConnection by receiving one in the class constructor. It's defined as Transient so that each object that needs a MySqlConnection receives a new one (and so that multiple objects aren't sharing the same MySqlConnection).

public class IndexModel : PageModel
{
    private readonly MySqlConnection _connection;

    public IndexModel(MySqlConnection connection)
    {
        _connection = connection;
    }

    public async Task OnGet()
    {
        await _connection.OpenAsync();
        // ...
    }
}

If you're not using Dependency Injection, then you don't need the ConfigureServices method. Most documentation "says 'do this' without any reason" because it's just assumed that that's how a typical ASP.NET Core 6 web application is authored.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1