Context Dispose should be used in ASP.NET MVC?

Asked

Viewed 539 times

2

In the Web Forms every time I’ve assembled some kind of CRUD, used the using to make an implicit Dispose().

public List<Produtos> Lista ()
{
    using (var ctx = new DbContext())
    {
        return ctx. Produtos.ToList();
    }
}

In ASP.net MVC this is done in what way?

public ActionResult Lista ()
{
    DbContext ctx = new DbContext ();
    return View ( ctx. Produtos );
}
  • Take a look at this link and see if it helps you http://stackoverflow.com/questions/1380019/asp-mvc-when-is-icontroller-dispose-called

2 answers

4


You can do it the same way, but it’s not necessary. The process executed is ephemeral and there will be the release of resources after its completion, this is guaranteed by framework then the first form is correct.

Note that this occurs only by the ephemeral nature of its functioning. There will be no manual release. If there is any reason to think (probably there is something wrong) that you need to release before everything is finished, then the second way is more interesting. I put this more for completeza of information. Normally you will let the EF take care of it for you.

Read more and yet here.

3

In MVC you can use it like this, which is the way I see it most in CRUD projects

public ActionResult Index()
{
    using (var db = new Contexto())
    {
        return View(db.Produtos.ToList());
    }
}

Remembering that Actionresult can return only View() with no object.

Although there are projects that I’ve seen that the connection context is outside the Actions as a variable of controller, but it goes of taste and needs of the project.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.