I'm refactoring a .NET AWS Lambda project with MySql.Data in it for connecting to AWS Aurora. I implemented the DI process and registered MySqlConnection into DI container as Transient and injected it into the DataAccess service.
The registration of MySqlConnection and the DataAccess go something like this:
Startup:
services.AddTransient<MySqlConnection>(provider =>
{
//Get the necessary parameters and build a connection string.
return new MySqlConnection(connectionString);
});
services.AddSingleton<IDataAccess, DataAccess>();
DataAccess:
private readonly MySqlConnection _connection;
// inject the MySqlConnection.
async function()
{
await _connection.OpenAsync();
await _connection.DoStuff();
await _connection.CloseAsync();
}
My boss concerned that all of the DB interaction will be going through a single connection that is injected into the DataAccess class and she doesn't want the db to crash because I'm not cleaning up the connections properly.
I have a few questions:
- I see the old code base has the using statement when it create a new MySqlConnection but I don't see one on the MySql documentation. Do I need the "using" statement when I create a new MySqlConnection?
- Should I register MySqlConnection as Transient and use DI or simply create a new MySqlConnection instance inside the class that use it?
- Is the DI of the DB connection going to leave a lot of open connections? Or, on the other extreme, that a single connection is going to slow down the lambda because it used to make numerous connections?
Thank you!