Why use the using block in ASP.NET MVC?

6

Does the using {} block work in the same way in both web and desktop applications in the sense that when we use it in controller ? It is a good practice to declare it in actions that there is contact with database Follow examples, which one would be a good practice?

public class UsuarioController : Controller
{
private EntidadesDCSystem db = new EntidadesDCSystem();

   [HttpPost]
   public ActionResult Adicionar(Usuario usuario)
   {
        if (ModelState.IsValid)
        {
            db.Usuario.Add(usuario);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(usuario);
    }

Or:

public class UsuarioController : Controller
{

   [HttpPost]
   public ActionResult Adicionar(Usuario usuario)
   {
      using (EntidadesDCSystem db = new EntidadesDCSystem())
      {
          if (ModelState.IsValid)
          {
             db.Usuario.Add(usuario);
             db.SaveChanges();
             return RedirectToAction("Index");
           }

           return View(usuario);
      }
   }
    
asked by anonymous 21.10.2015 / 18:09

4 answers

7
Does the using {} block work in the same way in both web applications and desktops in the sense that when we use it in the controller ?

Yes.

About the examples

This is good when you have multiple Actions in Controller :

public class UsuarioController : Controller
{
    private EntidadesDCSystem db = new EntidadesDCSystem();
    ...

The life cycle of a Controller begins and ends within a request. Because DbContext implements IDisposable , of course, that by closing the life cycle, your connection to the database and other data will be gracefully discarded.

using also does this: it forces the developer to implement IDisposable on the object involved in using , that is, to have a correct procedure for discarding the object.

In Controller , little changes whether you use the context as a private object or within a using block, since a Controller is an object with a life too short, which does not stay long in memory.

    
21.10.2015 / 18:19
6

When you use the using statement, you are telling the compiler that the feature you are using will no longer be used after the key closes, this ensures that the object went to the Garbage Collector > and that the Dispose() method of the object was called.

In the case of context (EntityFramework), connections to database and etc., the Dispose() method is where the resources used by the connection class are freed from memory.

Another benefit is to ensure that the referenced object is used only in that piece of code, preventing it from being referenced after it has been dropped (when it generates a NullReferenceException).

In some cases this may generate a performance gain, but in the case of controllers the gain is not very large, since the asp.net application lifecycle is very short (as the Cigano said, it starts and ends in a request).

See the Microsoft Reference: link

    
21.10.2015 / 18:17
6
  

Does using using {} work in the same way in both web and desktop applications in the sense that when we use it in the controller?

Yes , works the same way.

The using is nothing more than a try finally , where in the block finally is called the Dispose() of the object, so this only works with objects that implement IDisposable .

Do this

using (EntidadesDCSystem db = new EntidadesDCSystem())
{
}

It's the same thing to do

EntidadesDCSystem db;
try
{
    db = new EntidadesDCSystem();
}
finally
{
    db.Dispose();
}
    
21.10.2015 / 18:15
5

Especially this using should be used in any C # code. It ensures the release of resources and is essential to avoid resource leakage issues. This is a language feature, not something that was done for desktop or web. Use whenever the object uses some external resources that need to be released.

But in this case the resource release will occur quickly, so its use can be dispensed with by simplifying the code.

Reading the documentation is necessary to know when to use it. Some tools, like Resharper, like alerting you when you forgot to do this. Anything that uses the interface IDisposable should use using or otherwise simulate it, after all internally it is only try-finally .

There is another using to "import" namespaces , which is also useful in any type of application. Although it is the same word, the uses are quite different.

    
21.10.2015 / 18:18