views:

282

answers:

2

As seems to be popular at the moment, if you implement a repository as simply

IQueryable<T> FetchAll<T>();

using LINQ to SQL, then the repository must set up a DataContext which remains available outside of the repository.

So my question is, How does the DataContext get Disposed? What if an exception is generated by the code outside of the repository? Will it be leaking database connections?

Thanks

A: 

Make your repository implement IDisposable (and Dispose of the DataContext when the repository is Disposed). Now the API for your repository is something like

using (var repository=new MyRepository) //or use a ServiceLocator or Factory
{
    var myObjects = repository.FetchAll().Where(obj=>obj.Foo == "bar");
    //do something with myObjects
}

And now your repository will properly dispose of your DataContext and all is well in the world.

Mike Brown
Hey Mike, I this kind of thought in the back of my mind, but not yet seen it anywhere. All the books/blogs etc. just use IQueryable straight up. Is making the repository IDisposable 'the done thing'?
RR
Looks like it's a moot point. But making your repository Disposable allows you to do tricks like keeping the ObjectContext around for attaching new objects to it, and creating transactions.
Mike Brown
+3  A: 

Why you dont need to call dispose on DataContext

Summary the DataContext opens a connection when the query is called (when you access the data), and closes it when the query is over.

CSharpAtl
Thankyou, that is great!! I knew I must be missing something as nowhere have I seen any examples that expose IQueryable<T> dispose the DataContext
RR