DbContext and IDisposable

I like to call the DbContext “the centerpiece of Entity Framework” and I do not say it as a joke, we certainly know that in order to work with the schema of our database, we must use the DbContext (be it adding DbSet properties or using the Fluent API), but also to work with data we will use the DbContext, or more specifically, the class that inherits from DbContext, that is, the class that we call Context.

When we read, insert, update or delete data in our database through the Entity Framework, we will do it through the Context class. The typical use we will make of the DbContext is that we will instantiate it, we will use it, and then we will destroy it immediately. To do this we will use the using statement.

The idea of ​​the using statement is that we enclose the instance of a class within a block of code, and when we finish working with that class, then all the resources that the object was using are going to be released. If a class implements the IDisposable interface, and we instantiate it through a using, then at the end of the block the Dispose method will be called, which will be responsible for releasing any resource that uses the object. The DbContext class implements the IDisposable interface, so it is generally advisable to use it with the using statement.

In code, this looks like this:


using (var context = new ApplicationDbContext ())
{

} // <--- when we reach this line, any resources used by the context object will be released

In our case, ApplicationDbContext inherits from DbContext.

As you can see, we are making an instance of the ApplicationDbContext class inside the parentheses of a using statement, which causes that when we leave the code block defined by the using, all the resources used by the context object will be released. One of the most important things that gets release while doing the disposal is the connection to the database. Because connections are a limited resource, it is in your best interest to dispose them as early as possible.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s