Reputation: 2812
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)
{
db.Dispose();
}
base.Dispose(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?
Upvotes: 13
Views: 13695
Reputation: 4540
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/
Upvotes: 5
Reputation: 1092
In terms of best practices, you should absolutely use the template scaffolded stuff and not mess with the using(){}
pattern unless you have some really good overriding reason. Both solutions produce the same result, but both are not good solutions. The reason why the template has a single DbContext is to make it easier to test - heres an example:
public class SomeController : Controller
{
private ApplicationDbContext db;
public AccountController()
{
db = new ApplicationDbContext();
}
public AccountController(ApplicationDbContext context)
{
db = context;
}
}
The first constructor with no arguments is that which is used in production and automatically creates a new db context based on the app config file. The second allows you to inject a mocked db context when you are doing unit testing.
At the end of the day, this question and my answer isn't really about disposing db contexts - it's about why the code template designers chose to take the approach they did and why it will help you. You should read more on unit testing.
Upvotes: 2
Reputation: 1145
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:
Upvotes: 8
Reputation: 8271
A Using statement calls the Dispose() method at the end of the Using block automatically. The Using statement calls the Dispose() method even if there was an error in the code.
Upvotes: 1