Why does no one disposes DbContext after WebApi controller operation?

Prime case for using, no matter how the method is exited, your DbContext will be disposed;

public HttpResponseMessage GetInternet(int id) {
    using(var context = new InternetDbContext()) {
        var result =
           (from internet in context.Internets
            where internet.Id.Equals(id)
            select internet).FirstOrDefault();
        if(result != null)
           Request.CreateResponse(HttpStatusCode.OK, result);
    }
}

Sometimes it is a bad idea to dispose the context. For example, I have a WebAPI2 controller method like this,

    [Route("Questionnaires")]
    public IEnumerable<Questionnaire> GetAllQuestionnaires()
    {
        NMQContext context = new NMQContext();
        return context.Questionnaires.AsEnumerable();
    }

The result data is a JSON list, and the Questionnaire is a compound object -- it contains entities from multiple database tables. If I wrap this with "using" I get an error, such as

   "Message": "An error has occurred.",
   "ExceptionMessage": "The operation cannot be completed because the DbContext has been disposed.",

If you are trying to serialize compound objects, then it is better NOT to dispose the connection. It is better to let the EF handle it for you. You could probably fix it by explicit eager loading, but that is painful. Don't do it.


Personally, whenever I see the type implements IDisposable, I'm almost certain that I'm going to use a using statement when working with new instances of this type.

When the variable goes out of scope (like in your case with the context variable going out of scope when the execution returns from GetInternet method), its memory is eventually going to be reclaimed by garbage collector but this doesn't mean that any native handlers (e.g. file handlers or database connections) are going to be closed which can have a very serious negative impact on your application.

So, consider always wrapping an IDisposable into the using construct:

using (var context = new InternetDbContext())
{
  // Your code goes here
}

Hope this helps.