.NET Tips and Tricks

Blog archive

Disposing of the DbContext Object

I have two separate styles for using the DbContext object. In one style I create the DbContext object when my class is instantiated, either as part of defining a field for my class:

Public Class Customer Repository
  Dim db As New CustomerEntities

Or in my class's constructor:

Public Class Customer Repository
  Dim db As CustomerEntities

  Public Sub New()
    db = New CustomerEntities
   End Sub

I use this style when all the methods in the class us the DbContext object and I expect the methods to be called independently of each other (and in a variety of different combinations). I shouldn't admit this, but I frequently forget to call the Dispose method at the end of those methods.

My other style is to leverage the Using keyword, like this:

Using db = New CustomerEntities
  '...use CustomerEntities
End Using

This is the style I follow when my Entity Framework code is integrated with other processing (typically, other EF code). The primary reason I use Using in this style is to ensure that the Dispose method is called -- the End Using statement that marks the end of the block will make sure that happens. Basically, I'm compensating for my failures in the previous style.

It turns out that I needn't have felt bad about those missing calls to Dispose. A few quick tests with performance monitor will show that it's difficult (I would say "impossible") to detect any difference between applications that call the DbContext's Dispose method and those that do not.

There is, as always, one exception: when you take control of opening and closing the Connection object available through the DbContext object. In that scenario, it's entirely possible that you may forget to close your open Connection, something that DbContext won't let happen if you leave control of the Connection up to it.

Leaving a Connection open is bad because it defeats connection pooling (an open Connection object ties up a connection at the database, forcing other applications to create new connections at the database). Calling the Dispose method ensures that your Connection is closed.

So, as long as you let DbContext manage your connections, feel free to ignore the Dispose method. On the other hand, if you're managing your Connections, the Dispose method may be your bestest friend.

Posted by Peter Vogel on 06/18/2018


comments powered by Disqus

Featured

Subscribe on YouTube