返回XMLReader

时间:2010-01-11 17:18:12

标签: .net xml xmlreader

我试图从调用存储过程来运行FOR XML查询的数据访问类返回XMLReader。问题是,当我返回xmlreader或读取将终止时,我无法在sql连接上调用close()。调用xmlreader的类对sql连接一无所知,因此它不能负责关闭连接。我怎么处理这个?

2 个答案:

答案 0 :(得分:3)

您可以构建XmlDocument并将其返回,这样您就可以关闭该数据库连接。

答案 1 :(得分:1)

使用匿名方法打包电话。

例如,假设您有一个数据层类,请向数据层添加类似的方法:

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();
    });

它使代码更好,更易读,同时仍然保持组织和分层;