internal static async Task TryEnsureConnected()

in src/SqlBindingUtilities.cs [313:342]


        internal static async Task<bool> TryEnsureConnected(this SqlConnection conn,
            bool forceReconnect,
            ILogger logger,
            string connectionName,
            CancellationToken token)
        {
            if (forceReconnect || conn.IsBrokenOrClosed())
            {
                logger.LogWarning($"{connectionName} is broken, attempting to reconnect...");
                try
                {
                    // Sometimes the connection state is listed as open even if a fatal exception occurred, see
                    // https://github.com/dotnet/SqlClient/issues/1874 for details. So in that case we want to first
                    // close the connection so we can retry (otherwise it'll throw saying the connection is still open)
                    if (conn.State == ConnectionState.Open)
                    {
                        conn.Close();
                    }
                    await conn.OpenAsync(token);
                    logger.LogInformation($"Successfully re-established {connectionName}!");
                    return true;
                }
                catch (Exception e)
                {
                    logger.LogError($"Exception reconnecting {connectionName}. Exception = {e.Message}");
                    return false;
                }
            }
            return true;
        }