As the other answer explains, the using
clause isn't a natural fit for something you're wanting to re-use. However I had the same idea - I would still like to use this type of pattern to auto-open & auto-close the connection. If that is what you were hoping to do, then the key is that the object you are "using" cannot be the OracleConnection itself since you do want to reuse this, and "using" it will kill it. You really just want a new object which opens the connection on creation, and closes the connection on Dispose, and nothing more. This should do the trick (I am using it for my own purposes):
internal class OpenedContext : IDisposable
{
private OracleConnection _connection;
public OpenedContext(OracleConnection conn) {
_connection = conn;
if (_connection.State != System.Data.ConnectionState.Open) _connection.Open();
}
public void Dispose() {
if (_connection.State != System.Data.ConnectionState.Closed) _connection.Close();
}
}
And then in your example you could do something like...
// Early on...
OracleConnection _connection = DbConnectionsManager.GetDatabaseConnection(aDbConnectionString);
// ... Later on, in various other calls ...
using (new OpenedContext(_connection))
{
OracleCommand command = _connection.CreateCommand();
string sql = "SELECT * FROM MYTABLE";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
string myField = (string)reader["EXAMPLE"];
Console.WriteLine(myField);
}
}
Although it's goofy in a way, I definitely prefer setting up a pattern like this to always expecting future coders to manually "wrap" the re-open & re-close around every database call. It's more readable (or ignorable) and less risky (if you're greatly concerned about leaving the connection closed while idle).