I'd like to share the whole solution I've implemented to avoid checking the connection at every call. If the connection string is wrong an exception stops the execution, otherwise the attempt to open the connectionstring is done just once for each connectionstring.
Since the connection is often multithreaded I've added a syncobj used by the lock
which checks
#if DEBUG
private static object syncobj = new object();
private static ConcurrentDictionary<string, bool> CheckedConnection = new ConcurrentDictionary<string, bool>();
private static void CheckCanOpenConnection(SqlConnection connection)
{
lock (syncobj)
{
try
{
CheckedConnection.TryGetValue(connection.ConnectionString, out bool found);
if (found)
{
return;
}
else
{
connection.Open();
var canOpen = connection.State == ConnectionState.Open;
connection.Close();
CheckedConnection.TryAdd(connection.ConnectionString, true);
return;
}
}
catch
{
throw new ApplicationException("Unable to connect to: " + connection.ConnectionString);
}
}
}
#endif
Here is the call to from the method which instantiate the connection
private SqlConnection CreateConnection()
{
if (_connection == null)
{
_connection = new SqlConnection(this.ConnectionString);
#if DEBUG
CheckCanOpenConnection(_connection);
#endif
}
return _connection;
}