Why use block using in ASP.NET MVC?

Asked

Viewed 542 times

8

The block using {} works in the same way in both web applications and desktops in the sense of when we use it in controller? It is a good practice to declare it in the actions that there is contact with the database Following are 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);
      }
   }

4 answers

9


The block using {} works in the same way in both web applications and desktops in the sense of when we use it in controller?

Yes.

About the examples

This one is good when you own several Actions in the Controller:

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

The life cycle of a Controller starts and ends within a request. How DbContext implements IDisposable, of course, at the end of the life cycle, your connection to the database and other data will be disposed of gracefully.

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

In the Controller, little changes whether you use the context as a private object or inside a block using, given that a Controller is an object with a very short life cycle, which does not stay long in memory.

5

The using {} block works the same way in both web and desktop applications in the sense of when we use it in the controller?

Yes, works the same way.

The using is nothing more than a try finally, where on 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 as doing

EntidadesDCSystem db;
try
{
    db = new EntidadesDCSystem();
}
finally
{
    db.Dispose();
}

5

When you use the instruction using, you are telling the compiler that the resource you are using will no longer be used after the key has been closed, this ensures that the object went to the Garbage Collector and that the method Dispose() of the object was called.

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

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

In some cases this can generate a performance gain, but in the case of controllers the gain is not very large, since the life cycle of Asp.net applications is very short (as said by Gypsy, starts and ends in a request).

See the Microsoft reference: https://msdn.microsoft.com/pt-br/library/yh598w02.aspx

  • It depends a lot. The Controller is usually discarded very quickly because it only exists within the life cycle of the request, so this performance gain is very small.

  • Really Gypsy, this view is valid, yet another important benefit of using is to ensure that the object is used only where it is needed, if you try to use the object outside of using the compiler neither compiles nor generates an error. This prevents someone who has picked up the code from later trying to access it further.

  • Yes, but let’s assume one Controller great, okay? I don’t know, with 15 Actions. You would have to declare the block 15 times. There is not much practical basis. Also, as the dispose of Controller does Disposis in everything it implements IDisposable, the dispose of the context will end up happening anyway.

  • It makes sense, but the most important thing is to know the concept and apply it in the best way. I can have a controller with 15 actions, but only in a work directly the bank, in this case it would not make sense to instantiate the context and give Dysplasia. Each case is a case, but its answer is more applicable to the concept of the question.

4

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 made for desktop or web. Use whenever the object uses some external resources that need to be released.

But in this case the release of the resource will occur quickly, so its use can be waived, simplifying the code.

Reading the documentation is necessary to know when to use it. Some tools, like Resharper, like warning when you forgot to do this. Everything that adopts the interface IDisposable should use the using or another way that simulates him, after all he is only one try-finally.

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

Some readings that may help:

  • What is wrong here?

  • No. A Controller is an object whose life cycle is very small, being quickly discarded after processing its actions. So the second way "is not the only correct".

  • @Ciganomorrisonmendez improved?

  • 1

    No, look at that. The dispose context will always happen, regardless of using the using or not. It is common Controllers have, I don’t know, 10 Actions, all using context. Each request usually calls a Action only (sometimes they call more than one). In this case, the problem in the second way is that you have to declare the block for all Actions, which, in addition to being impractical, does not provide any gain.

  • I would change to: "The two forms are correct, but in day-to-day practice, the first form is more used by the number of Actions in common that use the context".

  • It’s true. I’ve changed.

  • Okay, now yes. + 1.

Show 2 more comments

Browser other questions tagged

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