views:

335

answers:

2

I'm a total newbie at Entity Framework and ASP.Net MVC, having learned mostly from tutorials, without having a deep understanding of either. (I do have experience on .Net 2.0, ADO.Net and WebForms)

My current doubt comes from the way I'm instancing my Entities objects.

Basically I'm doing this in my controllers:

public class PostsController : Controller {

    private NorthWindEntities db = new NorthWindEntities();

    public ActionResult Index() {
            // Use the db object here, never explicitly Close/Dispose it
    }
}

I'm doing it like this because I found it in some MSDN blog that seemed authoritative enough to me that I assumed this was a correct way.
However, I feel pretty un-easy about this. Although it saves me a lot of code, I'm used to doing:

using (NorthWindEntities db = new NorthWindEntities() {
}

In every single method that needs a connection, and if that method calls others that'll need it, it'll pass db as a parameter to them. This is how I did everything with my connection objects before Linq-to-SQL existed.

The other thing that makes me uneasy is that NorthWindEntities implements IDisposable, which by convention means I should be calling it's Dispose() method, and I'm not.

What do you think about this?
Is it correct to instance the Entities object as I'm doing? Should it take care of its connections by opening and closing them for each query?
Or should I be disposing it explicitly with a using() clause?

Thanks!

+2  A: 

Controller itself implements IDisposable. So you can override Dispose and dispose of anything (like an object context) that you initialize when the controller is instantiated.

The controller only lives as long as a single request. So having a using inside an action and having one object context for the whole controller is exactly the same number of contexts: 1.

The big difference between these two methods is that the action will have completed before the view has rendered. So if you create your ObjectContext in a using statement inside the action, the ObjectContext will have been disposed before the view has rendered. So you better have read anything from the context that you need before the action completes. If the model you pass to the view is some lazy list like an IQueryable, you will have disposed the context before the view is rendered, causing an exception when the view tries to enumerate the IQueryable.

By contrast, if you initialize the ObjectContext when the Controller is initialized (or write lazy initialization code causing it to be initialized when the action is run) and dispose of the ObjectContext in the Controller.Dispose, then the context will still be around when the view is rendered. In this case, it is safe to pass an IQueryable to the view. The Controller will be disposed shortly after the view is rendered.

Finally, I'd be remiss if I didn't point out that it's probably a bad idea to have your Controller be aware of the Entity Framework at all. Look into using a separate assembly for your model and the repository pattern to have the controller talk to the model. A Google search will turn up quite a bit on this.

Craig Stuntz
Ok, that makes sense.Now, the question is...Am I doing things incorrectly?Do I really need to dispose of the Entities object?What happens if I dont? Will I be "leaking" connections to the SQL Server?
Daniel Magliola
ObjectContext.Dispose doesn't do much (see Reflector). But it's reasonable to presume that could change and you *should* dispose it.
Craig Stuntz
+1  A: 

You are making a good point here. How long should the ObjectContext live? All patterns and practises books (like Dino Esposito's Microsoft-NET-Architecting-Applications) tell you that a DataContext must not live long, nor should it be cached.

I was just wondering why not having, in your case, a ControllerBase class (I'm not aware of the MVC implementation, so bare with me) where the ObjectContext gets initiated once for all controller. Especially think about the Identity Map Pattern, that's already implemented by Entity Framework. Even though you need to call another controller as your PostsController, it would still work with the same Context and improve performance as well.

derSteve