0

I have the following code, where I want to immediately dispose of ApplicationDbContext instance:

using (var context = ApplicationDbContext.Create())
{
    MyRepository myRespository = new MyRepository(context);
    myRepository.ReadData();
}

If C# garbage collector wants to immediately dispose of ApplicationDbContext, it would have to immediately dispose of MyRepository as well, because it has a reference to ApplicationDbContext? Is this actually happening?

Or do I need to write my code like below to ensure ApplicationDbContext is Disposed, immediately?

using (var context = ApplicationDbContext.Create())
using (MyRepository myRespository = new MyRepository(context))
{
    myRepository.ReadData();
}
Hooman Bahreini
  • 14,480
  • 11
  • 70
  • 137
  • 1
    read this: https://gunnarpeipman.com/csharp-idisposable/ – jazb Oct 02 '19 at 08:21
  • 2
    `IDisposable` has nothing to do with the GC. There are lots of questions and answers on SO about this (e.g. [this one](https://stackoverflow.com/questions/45036/will-the-garbage-collector-call-idisposable-dispose-for-me)) - just search and read! – dymanoid Oct 02 '19 at 08:23
  • Is `MyRepository` disposable? –  Oct 02 '19 at 08:48
  • Basic rule I use: Is the class or object Disposable (implements `IDisposable`)? If yes, then apply a `using` or a `try...finally` block. If your own class uses disposable resources as a global variable, make your own class disposable. – Stefan Oct 02 '19 at 09:09
  • @OlivierRogier: Yes, MyRepository implements IDisposable – Hooman Bahreini Oct 02 '19 at 09:51

1 Answers1

1

Your second block of code is right.

One using clause is applied to one declaration.

Wat you wrote here:

using (var context = ApplicationDbContext.Create())
using (MyRepository myRespository = new MyRepository(context))
{
  myRepository.ReadData();
}

Is the same as:

var context = ApplicationDbContext.Create();
try
{
  var myRespository = new MyRepository(context);
  try
  {
    myRepository.ReadData();
  }
  finally
  {
    myRepository.Dispose();
  }
}
finally
{
  context.Dispose();
}

That's what the compiler generate for you, therefore you do not need to worry about writing such a heavy and repetitive thing which is a possible source of error and bugs.

In the first code, myRespository is not disposed.