My web application has the following class:
public class DatabaseProvider {
private readonly IDbConnection _cn;
public DatabaseProvider(IDbConnection cn) {
_cn = cn;
}
public void ExecuteNonQuery(string query) {
// Execute the query
var cmd = _cn.CreateCommand();
cmd.CommandText = query;
cmd.ExecuteNonQuery();
}
}
Where the IDbConnection dependency is declared using the following code (with Microsoft Unity):
container.RegisterType<IDbConnection>(new InjectionFactory(c => {
var cn = new SqlConnection("...");
cn.Open();
return cn;
}));
This allows me to swap out the connection to SQLite like so:
container.RegisterType<IDbConnection>(new InjectionFactory(c => {
var cn = new SQLiteConnection("Data Source=:memory:;Version=3;");
cn.Open();
return cn;
}));
I use SQLite when testing and the connection must remain open otherwise the data is lost. Therefore I can’t just open and close the connection when needed.
I have always opened the connection to the database when it was needed and was wondering whether this will scale for large applications?
I’d appreciate any advice on how this can be improved. Thanks
As a general rule in ADO.NET the connection must be closed as soon as possible.
Connections are re-used from connection pool and are scarce resource.
The recommended way to do this is with using () {} construct.
SQL Server Connection Pooling (ADO.NET)
We strongly recommend that you always close the connection when you are finished using it so that the connection will be returned to the pool. You can do this using either the Close or Dispose methods of the Connection object, or by opening all connections inside a using statement in C#, or a Using statement in Visual Basic. Connections that are not explicitly closed might not be added or returned to the pool. For more information, see using Statement (C# Reference) or How to: Dispose of a System Resource (Visual Basic) for Visual Basic.
So, I suggest that you make a interface IDbProvider and then make 2 implementations: SqlServerProvider and SQLiteProvider and handle opening and closing connections inside them. Then use Unity to bind one provider or another.