How to avoid a “DisposableFieldsShouldBeDisposedRule” defect on fields I don't want to dispose?

StackOverflow https://stackoverflow.com/questions/4538696

  •  13-10-2019
  •  | 
  •  

سؤال

There is a IDisposable which contains a field for the Logger:

class DoesNotDisposeMember : IDisposable {
  public IDisposable Logger { get; set; }

  public void Dispose ()
  {
    logger = null;
  }
}

Gendarme reports that there is a DisposableFieldsShouldBeDisposedRule-Defect, but I don't want to dispose the logger.

Can anyone help me?

هل كانت مفيدة؟

المحلول

Setting side why you wouldn't want to dispose of it; if you don't want to dispose of it, you probably should not be storing it in an IDisposable member, then. The only real purpose of that interface is to signify/enable that item being disposed.

If it's a logging object, is there not another common base interface/class you can use, such as one derived from Stream or StreamWriter?

Now that I've written that, it of course strikes me that this still includes IDisposable in the hierarchy... which I suppose brings us back to what I said I would set aside:

Why are you setting a variable here that you do not intend to dispose of? If you are disposing of it elsewhere, you should probably also use it there. The code that is wrapping the logger object should handle all the functionality of it, including exposing the separate interface to your model/business objects that enables logging.

Basically, if you are encapsulating the logging in another object, then you should not be referencing the internal logging stream object outside of that object. If you aren't encapsulating logging elsewhere, then this class should dispose of it appropriately.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top