Disposing an Injected Constructor Object

Suppose I have a class that is associated with another class. It will look something like this:

public class DisposableClassOne : IDisposable
{
   private class mDisposableClassTwo;

   public DisplosableClassOne(DisposableClassTwo dcTwoInjected)
   {
      mDisposableClassTwo = dcTwoInjected;
   }

   public void Dispose()
   {
      // Should I dispose here? or make caller dispose of dcTwoInjected
      //mDisposableClassTwo.Dispose();
   }
}

Should I call a method Disposefor mDisposableClassTwoor should I get the calling user to process it like this?

using(DisposableClassTwo dcTwoInjected = new DisposableClassTwo())
using(DisposableClassOne dcOne = new DisposableClassOne(dcTwoInjected))
{
   // do stuff with dcOne
}

I think that calling the caller is the best way, but I think that by placing the call in the Dispose method, it guarantees that it will be called. Is there a better way to handle this?

+3
source share
6 answers

I think this is the life decision you must make in your design.

DisposableClassOne , DisposableClassTwo?

DisposableClassTwo DisposableClassOne?

. StreamReader/Writer - : "" "" - Stream StreamReader , Reader , Reader .

, DisposableClassTwo - - , refernece , , " -". , , , DisposableClassOne .

+2

, , (1) , , . , , , .

, (), , - Dispose .

, , , , . , ( , ). ... , .


(1) , , , . - ( ) , .

+5

, , - . Dispose(bool disposing) . Dispose() Dispose(true), Dispose(false).

:

if (disposing)
{
    // Dispose of the referenced object, as well.
}

StreamWriter StreamReader . Dispose(), Stream. , .

: DisposeChild, true, , , .

rcravens. , .

+1

IDisposable, : " , , ". :

  • ( "" ), , . Dispose.
  • , , . Dispose, .
  • , # 1, , # 2, , , . , , , .
  • , , , , . .

, № 3. №4. - , , . . , , . , .

+1

- , .

. , , -:

/ #

0

" " , . .

, , , . Stream StreamReader - ... IDisposable, , . , ( , ).

The simplest answer is to have two users (), even if you go and do (and document!) That the second IDisposable will recycle the first.

0
source

Source: https://habr.com/ru/post/1782666/


All Articles