Dispose DbContext in MVC Controller, which way "better"?

asp.net-mvc entity-framework


In MVC 5, the scaffolding codes will have something like:

    public class MyController : Controller
    private MyContext db = new MyContext();

    protected override void Dispose(bool disposing)
        if (disposing)

otherwise, I need to have

using (var db = new MyContext())

in each action.

The codes look good, so I don't need to use using in each action. However, is this subject to preference of programmers, or such style has some advantage over using in each action that needs to use the dbcontext?

11/6/2014 7:26:19 AM

Accepted Answer

Both solution are good - both solution will dispose db context. But in my opinion the second option will be better - you create db context just where you have to.

But what if another class (some service class) also uses db context. It is good practice to have one db context for the whole web request. In that case you should pass previous created db context to all classes that use db context to prevent creating new db context in all clases. So I will consider usage of IoC containers. IoC container will resolve your dependencies and also will mange object lifetime. Bellow

I listed a few IoC containers:

11/3/2014 9:14:24 AM

Popular Answer

For simple scenarios calling Dispose (or using Using) is not necessary at all :) "The default behavior of DbContext is that the underlying connection is automatically opened any time is needed and closed when it is no longer needed." From here: http://blog.jongallant.com/2012/10/do-i-have-to-call-dispose-on-dbcontext/

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow