1

does MVC automatically dispose of the database context I instantiate in a controller or anywhere else or does it persist?

Do I need to use using or can I not worry about that?

Oded
  • 489,969
  • 99
  • 883
  • 1,009
Darren
  • 10,631
  • 8
  • 42
  • 64

2 Answers2

3

If you are talking about an EF data context, the answer is no, ASP.NET MVC, doesn't dispose it automatically but you shouldn't be worried about disposing it as Stephen Walther explains in his blog post. And here's a similar answer.

Community
  • 1
  • 1
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 1
    What about this argument? "I’d argue that anything which is IDisposable should be explicitly disposed; you should treat any class as a black box and not make assumptions about its internal implementation, which might change in a future release." – devuxer Mar 12 '12 at 16:46
  • 1
    I think this is dangerous advice. As a general rule I would say that if a type implements `IDisposable` you should call `Dispose` (or use a `using`). The intent on the "publicly visible surface" of the class is that you should call `Dispose`. Knowing some privileged information on why this doesn't apply (because you've decompiled it, or spoken to one of the devs on the team) seems a pretty shaky reason not to do it. For example, what if this behaviour changed in a future release? IMHO it is easier to just stick to the rule, unless you have a specific reason _not to_ – Rob Levine Mar 12 '12 at 16:47
2

Whenever initializing an object that is defined as IDisposable, you should wrap the creation in a using statement. This is a general good rule to follow and ensures disposal.

This includes your data context. If you don't and the controller throws in the middle of using the data context, you may end up with open connections.

Oded
  • 489,969
  • 99
  • 883
  • 1,009