This course will be retired on June 1, 2025.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
We've aligned the beginnings of the context and controller class lifetimes, but we still need to align the end of the context's lifetime to the end of the controller's lifetime. Let's see how to do that by disposing our context when the controller is disposed.
Follow Along
To follow along committing your changes to this course, you'll need to fork the dotnet-comic-book-library-manager repo. Then you can clone, commit, and push your changes to your fork like this:
git clone <your-fork>
cd dotnet-comic-book-library-manager
git checkout tags/v2.4 -b managing-the-contexts-lifetime
Keyboard Shortcuts
-
F5
- Start Debugging -
F9
- Set a breakpoint on the current line of code -
F10
- Step Over
Implementing a Dispose Method
For more information on how to implement the Dispose
method, see https://msdn.microsoft.com/en-us/library/fs2xkftw(v=vs.110).aspx.
Managing Entity Framework DbContext Lifetime in ASP.NET MVC
There are actually three ways to manage the lifetime of your database context.
-
using
Statement - Dispose Pattern
- Dependency Injection Container
In the Treehouse Entity Framework Basics course, we used using
statements. While in this course, we used the Dispose pattern. In a future workshop, we'll introduce dependency injection.
For more information about how to use dependency injection to manage the lifetime of the database context, see this blog post from Dave Paquette:
Managing Entity Framework DbContext Lifetime in ASP.NET MVC
Do You Always Have to Dispose Your Database Context?
In this course, we implemented the Dispose pattern in order to ensure that our database context was always properly disposed. But did we have to do that? As it turns out, it's not always necessary to call the Dispose
method on the database context object, but it's typically a good idea to do so. See this blog post from Jon Gallant for more information:
Do I always have to call Dispose() on my DbContext objects? Nope
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up