这是我为C#控制台应用程序设计的(非常简化以说明问题空间)设计.数据库连接实现IDisposable,此解决方案不允许using
数据库连接对象.有人可以为控制台应用程序提出更正确的结构吗?这是我经常需要解决的问题.
class Program { SQLiteConnection sourceConnection; SQLiteConnection destinationConnection; static void Main(string[] args) { Program shell = new Program(); // get connection strings from command line arguments string sourceConnectionString = shell.getConnectionString(args); string destinationConnectionString = shell.getConnectionString(args); // call non-static methods that use shell.setUpConnections(sourceConnectionString, destinationConnectionString); shell.doDatabaseWork(); } private void setUpConnections(string sourceConnectionString, string destinationConnectionString) { sourceConnection = new SQLiteConnection(sourceConnectionString); destinationConnection = new SQLiteConnection(destinationConnectionString); } private void doDatabaseWork() { // use the connections here } }
编辑:
有些人无法弄清楚为什么我要将它们作为成员变量.这是doDatabaseWork中的用例(有点伪问题):
foreach (Row sourceRow in DBResultSet) { string sourceXml = sourceRow.Columns["MyColumnName"].Value; string destinationXML = transformUsingXSLT(sourceXml); writeToDestination(destinationXml); }
看看我想如何在这个循环的生命周期中保持这些连接打开?
编写一个实现IDisposable的类怎么样?
在类构造函数中,您可以实例化数据库连接.
然后在IDisposable.Dispose方法中,编写用于关闭数据库连接的拆卸代码.
这是一个代码示例,用于演示我的意思:
public class DBWrapper : IDisposable { public SqlConnection Connection1 { get; set; } public SqlConnection Connection2 { get; set; } public DBWrapper() { Connection1 = new SqlConnection(); Connection1.Open(); Connection2 = new SqlConnection(); Connection2.Open(); } public void DoWork() { // Make your DB Calls here } public void Dispose() { if (Connection1 != null) { Connection1.Dispose(); } if (Connection2 != null) { Connection2.Dispose(); } } }
然后,从您的Program类的main方法中:
class Program { static void Main(string[] args) { using (DBWrapper wrapper = new DBWrapper()) { wrapper.DoWork(); } } }