c# – Bank connection is open in static method?


I have the following static class available for the entire application:

public static class MinhaClasse
   public static void Salvar(Item meuItem)
       using (MeuEntities db = new MeuEntities())

This is just an example, but my class necessarily needs to be static.

The question is:
As it is a static class and has a connection to the database, this connection is open all the time or is only opened when I call MinhaClasse.Salvar(Item); ?

I'm using Entity Framework .


MeuEntities is a class generated by the Entity Framework , inheriting from DbContext , right?

Connection lifecycle

Using the Entity Framework , you don't control the connection lifecycle but the context lifecycle. At specific times the context will request a connection to the database to search or persist entities.

The physical connection to the database is managed by ADO.Net , which maintains a connection pool to avoid creating a new connection every time the consumer needs one, with this it offers better performance as creating a connection with the database data is costly.

Keep the life of the context short and let the connection management with the Entity Framework and the ADO.Net it runs underneath.

And this you are already doing since you create the context just to persist and already get rid of it.

Relationship between the class being static and the connection lifecycle.

There is no relationship. The scope of the context or the fact that you get rid of it (either by invoking the dispose method or by instantiating it with using ) will affect the lifecycle of the connection. The fact that the class consuming the context is static has nothing to do with it.

Now, if you declare the context in a static variable and never get rid of it, then you can negatively affect the connection lifecycle.


Remove from your code the call to the dispose method because the using serves precisely to guarantee this call.

Scroll to Top