views:

179

answers:

2

I've been looking at the Nerd Dinner code and one thing they do in their models, is create an instance of the DataContext like this:

public class DinnerRepository {

    private NerdDinnerDataContext db = new NerdDinnerDataContext();

    public IQueryable<Dinner> FindUpcomingDinners() {
        return from dinner in db.Dinners
            where dinner.EventDate > DateTime.Now
            orderby dinner.EventDate
            select dinner;
    }

    // more methods below
}

These are used in the controllers like this:

public class DinnersController : Controller {
    DinnerRepository dinnerRepository = new DinnerRepository();

    public ActionResult Index() {
        var dinners = dinnerRepository.FindUpcomingDinners().ToList();
        return View("Index", dinners);
    }
}

But it doesn't seem that NerdDinnerDataContext ever gets disposed. Is this a problem that I should worry about? Or is this pattern OK?

Note: not the latest Nerd Dinner code, I know

A: 

In this case, this is a best practice. The Repository is returning an IQueryable object...which means processing of the query will be delayed until the result is needed.

If you dispose of the context in the Repository, when the calling code tries to retrieve the results from the IQueryable object, there will be no DataContext left.

Justin Niessner
In the specific case of MVC you know exactly when the IQuerable will be enumerated (when the view is executed). You also know that this happens *before* the controller is disposed. So if you have a context which needs to be disposed, you can do it safely.
Craig Stuntz
+4  A: 

It turns out that disposing the DataContext object is generally not something you want to do in a typical application.

see http://mostlytech.blogspot.com/2008/01/linq-datacontextdispose.html (by Jon Skeet, of course) for a little more detail.

JasonTrue
Be careful; that's not generally applicable outside of L2S. Other ORMs may actually care that they're disposed.
Craig Stuntz
Fair enough, though I think most ORMs will require their own concrete implementation of the repository... certainly my NHibernate repositories require different code than my L2S or InMemory ones. (I don't spend much time with the Entity Framework, so I can't comment there).
JasonTrue