I have a method like this:
void Execute(SqlCommand cmd)
{
try
{
using(SqlConnection conn = new SqlConnection(...))
{
conn.Open();
cmd.Connection = conn;
// ...
}
}
finally
{
cmd.Connection = null;
}
}
It's used like this:
using(SqlCommand cmd = new SqlCommand(...))
{
Execute(cmd);
}
Is there anything behaviorally wrong with this? I know it's more usual to create the SqlConnection first, then the SqlCommand, but since SqlCommand is in reality more-or-less a plain old object I think it should be fine in practice.
Execute's job were to configure the command, perhaps. However, it is a method uses the command, and this is why it looks awkward. Having said that,IDisposable.Disposeshould work and not throw even if called multiple times.Executemethod like written here. Except in the legacy implementation, oneSqlConnectionis shared with alockused to control concurrent access. I'm trying to refactor to remove the lock and leverage built-in connection pooling in the least invasive way possible.