Managing the Context's Lifetime5:11 with James Churchill
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.
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
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.
- 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:
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:
You need to sign up for Treehouse in order to download course files.Sign up