I have a project on MVC. We chose EF for our DB transactions. We created some managers for the BLL layer. I found a lot of examples, where "using" statement is used, i.e.
public Item GetItem(long itemId)     {         using (var db = new MyEntities())         {             return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault();         }     }   Here we create a new instance of DBcontext MyEntities(). We using "using" in order to "ensure the correct use of IDisposable objects."
It's only one method in my manager. But I have more than ten of them. Every time I call any method from the manager I'll be using "using" statement and  create another DBcontext in the memory. When will the garbage collector (GC) dispose them? Does anyone know?
But there is alternative usage of the manager methods. We create a global variable:
private readonly MyEntities db = new MyEntities();   and use DBcontext in every method without "using" statement. And method looks like this:
public Item GetItem(long itemId) {     return db.Items.Where(it => it.ItemId == itemId && !it.IsDeleted).FirstOrDefault(); }   Questions:
usage" statement (because it affects the performance) - GC will do all for that?I'm a "rookie" in EF usage and still haven't found the unequivocal answer for this question.
EF and EF Core DbContext types implement IDisposable . As such, best practice programming suggests that you should wrap them in a using() block (or new C# 8 using statement). Unfortunately, doing this, at least in web apps, is generally a bad idea.
The using statement causes the object itself to go out of scope as soon as Dispose is called. Within the using block, the object is read-only and can't be modified or reassigned. A variable declared with a using declaration is read-only.
The using statement guarantees that the object is disposed in the event an exception is thrown. It's the equivalent of calling dispose in a finally block.
First, DbContext is a lightweight object; it is designed to be used once per business transaction. Making your DbContext a Singleton and reusing it throughout the application can cause other problems, like concurrency and memory leak issues. And the DbContext class is not thread safe.
I think you will find many suggesting this style of pattern. Not just me or Henk DBContext handling
For some performance tips, well worth a read
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With