c# – Is the singleton approach recommended for Azure SQL DB?
We are Azure SQL DB.
Right now we are creating, open & close connection for every incoming request. Like below
on Startup.cs
builder.Services.*AddScoped*<IDbConnection>(_ => new SqlConnection(""));
builder.Services.*AddScoped*<Func<IDbConnection>>(svc => () => svc.GetRequiredService<IDbConnection>());
on clientimpl.cs
private readonly Func<IDbConnection> _connectionFactory;
using (var connection = _connectionFactory())
{
//check status before open
if (connection.State == ConnectionState.Closed)
connection.Open();
finally
{
connection.Close();
}
}
Instead of above approach,
Thought of creating the singleton sql conn objection and reusing the same instance through out the application lifetime rather creating, open & close connection for each & every request.
Is the singleton approach recommended for Azure SQL DB?
Are there any considerations?
builder.Services.AddScoped(_ => new SqlConnection(“”)); recommeded than builder.Services.AddSingleton(_ => new SqlConnection(“”));
Read more here: Source link