Search code examples
c#asp.net-mvclinqnerddinner

Do the Nerd Dinner models use best practices for disposing objects?


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


Solution

  • 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.