这是我为 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);
}
看看我想如何在这个循环的生命周期内保持这些连接打开?