How to avoid repeating "using" in ASP.NET MVC?

Asked

Viewed 151 times

5

I have a controller where several moments have a code similar to this:

    public ActionResult ListarProduto()
    {
        using (DBModels db = new DBModels())
        {
            return View(db.Produto.ToList());
        }

    }

How not to repeat this using?

  • The ideal would be to receive maintain the life cycle of the DBModels by request.

  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful to you. You can also vote on any question or answer you find useful on the entire site

1 answer

8

You are not repeating :) I imagine you want not to use in others actions, right? That being the question maybe it’s not just the using. It itself is not the problem, and the solution just to eliminate it would probably be worse, you would have to create an object to manage it or create a method probably receiving an anonymous function to perform, in general it will only complicate.

You could be looking at the wrong loop. Repeating a very short chunk of code that does not create a canonical knowledge is no problem at all and should not worry about it. DRY is for something else. There are techniques to do this, but it doesn’t always pay. One of them is the Dependency injection, but should only be used for other reasons not to repeat a very small chunk of code.

If you want to reduce repetitions of more relevant code that has a semantics, and not just the using then it can be interesting to have a method apart, probably private that can be called by the various actions. It doesn’t seem to be what you want, but the information stays.

Having said all this in MVC almost always does not need the using. Its execution is ephemeral and the resource will be discarded anyway. The resource does not stay alive when the application stops running. I do not say that in any case can do this without problems, especially in case that the execution is not as simple as the example shows and does several other things (but it needs to be a lot, it is rare).

Just to complement today, in C# 8, you can write like this too:

public ActionResult ListarProduto() {
    using var db = new DBModels());
    return View(db.Produto.ToList());
}

In case the question could not even do this, can only:

public ActionResult ListarProduto() => new DBModels().View(db.Produto.ToList());

I put in the Github for future reference.

Has more information on Difference between instantiating class and using. There you have it links with more details on the using if that’s of interest.

Browser other questions tagged

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