我正在尝试从一个数据访问类返回一个XMLReader,该数据访问类调用一个存储的proc来运行一个FOR XML查询。问题是,当我返回xmlreader时,我不能在sql连接上调用close(),否则读取将终止。调用xmlreader的类不知道任何关于sql连接的信息,因此它不能负责关闭连接。我该怎么处理呢?
发布于 2010-01-12 01:21:04
您可以构建一个XmlDocument并返回它,这样就可以关闭该数据库连接。
发布于 2010-01-12 02:11:58
使用匿名方法包装调用。
例如,假设您有一个datalayer类,向该数据层添加一个类似的方法:
public delegate void DoSomethingInvoker();
class DataLayer
{
//myReader needs to be declared externally in other to access it from the doSomething delegate
public void MethodThatGetsAsXmlReader(XmlReader myReader, DoSomethingInvoker doSomething)
{
myReader = GetXmlReaderFromDB();
doSomething();
CloseDbConnection(); //close connections, do cleanup, and any other book keeping can be done after the doSomething() call
}
}要调用/使用它,只需在您的高级类中执行此操作
DataLayer dl = new DataLayer();
XmlReader myReader = null; //variables declared outside the scope of the anonymous method are still accessible inside it through the magic of closures
dl.MethodThatGetsAsXmlReader(myReader, delegate()
{
//do all work that involves myReader here
myReader.read();
Console.out.println(myReader.value);
});
//at this point myReader is closed and cannot be used基本上,您将想要执行的代码传递给数据层,数据层获取xmlreader,针对它调用您的代码,然后进行清理。
我在代码中使用了类似的技术来包装事务逻辑
DataLayer dl = new DataLayer();
dl.Transaction(delegate()
{
dl.DbCall1();
dl.DbCall2();
dl.DbCall3();
});它使代码看起来更好、更具可读性,同时保持代码的条理性和层次化;
https://stackoverflow.com/questions/2043494
复制相似问题