I have a Repository class that has a DBContext. Should we close the DbContext after the transaction? That is, should my Repository class implement IDisposable
(so that I dispose of the DBContext) and should I enclose my Repository class in a ùsing
statement?
Or does DBContext manage its own lifecycle and not disposing of it will be okay?
Should not need using statement if you set it up using in the DI container as Scoped.
SaveChanges/SaveChangesAsync already does this for you and it’s most of the time enough. It tracks all changes and all have to go through or none will. You can start transactions and do rollbacks as well, but I’ve never needed to since I always call SaveChanges once per request. However, it can be good if you have more than one context and need to make sure all changes go through to every database, since you may share a transaction between contexts.
https://docs.microsoft.com/en-us/ef/core/saving/transactions
Also, I recommend ditching the repository and use the DbContext in your handler if you want to use EF. Using a repository pattern over EF is pointless. Otherwise, you might as well go with Dapper and write SQL.
A repository pattern with EF isn’t pointless if you consider EF as part of the data layer and something you might want to swap out.
Only ditch repositories if you’re 100% sure you won’t switch to another ORM.
DB context is supposed to run the GC automatically, however, I have had issues with locks and concurrency, especially if using it as an injection.
I found that doing the following seems to force the GC to run.
Public async task<whatever> saveUser(model user) { using( Var context = new applicationDBContext) { // DO STUFF
await context.SaveChangesAsync();
}
}
Sorry on mobile, so excuse formatting and syntax, but this causes the context to be GC correctly.