Reputation: 111
From my understanding, when you register a DbContext using AddDbContext it is registered as scoped lifetime which means one DbConnext per http request. And that you don't need to use a using statement because the connection will be closed and cleaned up for you if you are not performing long running db calls. But when is the connect to the database opened? Does it open/close the connection automatically after each db call or is the connection opened at the time the DbContext is injected into a service and closed when the request finishes?
The reason I ask is because I am rewriting an existing app that uses both classic asp and ASP.NET 4.8 (using EF and Microsoft Enterprise Data Library). I had previously implemented repositories/services and had the DbContext in a repository where all the calls in that repository used EF. Other repositories use sql statements using dapper. I was asked to remove the repositories and use our old method of creating separate DataAccess files (each implement the same partial class) and named based on the database being used and not functionality. I really don't like this idea because we have projects where there are 100s of database calls in one file because they happen to use the same database (some even using multiple databases) and we end up with DataAccess methods that are very similar/same but named differently. I refactored the repositories to follow this pattern. Since all the files implement the same partial class, I had to inject the DbContext into the constructor; which a good chuck of the database calls will not use. After doing so, I started wondering if the calls that don't use EF will now have an extra open db connection for no reason.
Upvotes: 2
Views: 2272
Reputation: 9092
But when is the connect to the database opened?
From this we can see:
By default the a single DbContext will be created and used for each HTTP request. A connection can be opened and closed many times during the lifetime of a DbContext, but if the DbContext starts a transaction the same underlying connection will remain open and be reused for the lifetime of the transaction.
When you create a DbContext it's not immediately initialized, nor is its connection immediately opened.
It opens a connection when loading or saving and closes it once it's done. If you force it by starting a transaction and keeping it open, the connection will be opened during DbContext lifetime .
see this to know more.
Upvotes: 2