开发者

Does DataService implement IDisposable?

Here is an example service:

public class MyWcfDataService : DataService<MyEFModel>
{
   [WebGet(ResponseFormat = WebMessageFormat.Json)]
   public IQueryable<GetMyListEF> GetMyList()
   {
      using (MyEfModel context = this.Cu开发者_JAVA技巧rrentDataSource)
      {
          return context.GetMyListEF().ToList().AsQueryable();
      }
   }
}

Should I be using the using statement? It kinda makes IQueryable pointless since I have to cast it to a List first (I do this because other methods call the GetMyList method and without casting to a list first, the data is gone [because of deferred execution])

I thought I've read somewhere (can't find the link now) that WCF Data Services don't implement IDisposable. If this is true then the using statement is pointless.


The using statement will cause your CurrentDataSource to be disposed at the end of the using block, not when the DataService is disposed. Therefore it's not a question of whether the DataService is IDisposable (it isn't), but whether MyEfModel is disposable (it is). As Mr. Disappointment points out, the compiler would prevent your using the using statement if this were not the case.

This means that the using block is best used when you create a new object. For example:

using (MyEfModel context = this.GetNewDataSource()) {...}

That way you don't run into the possibility that someone will try accessing CurrentDataSource after the using block and encountering an exception.

Regarding your other point about IQueryable and such, I haven't typically seen WCF methods implement IQueryable<>, since they're consumed over a network connection. Usually IEnumerable<> is preferred. And you're not "casting" your query to a List, as that would imply it was already in a list. You are evaluating the query to create a List. Then you might cast that list to an IEnumerable or IQueryable because List implements those interfaces.


I ended up going with this:

[WebGet(ResponseFormat = WebMessageFormat.Json)]
public IQueryable<GetMyListEF> GetMyList()
{
    return this.CurrentDataSource.GetMyListEF();
}

The using statement isn't needed because the WCF Data Service will dispose the CurrentDataSource at the end of the request. Using IQueryable also allows utilization of lazy loading aka deferred execution.

Here is another post on this: Proper way to return IQueryable using WCF Data Service and EF

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜