I am creating a .NET API and one of my methods returns a Stream . I need to ensure that some other class is deleted when the caller returns the Stream that I am returning.
The only way I can do this is to create a wrapper class that inherits from Stream and tacks on the functionality I need, delegating everything else to the underlying Stream .
I don't like decorating the framework class simply because it can get new members in future versions of .NET that I will need to upgrade to support the API.
Is there a better way to do this?
Example
Here is a concrete example of your thinking.
Keep in mind that one of the requirements of this class is that it cannot require removal by referencing the ContentSource class in this example.
public class ContentSource { public Stream OpenRead() { var entry = GetEntry();
Stream Packer Example
This is a decision I can think of that doesn't suit me.
public sealed class DependencyDisposingStreamWrapper : Stream { private readonly Stream _stream; private readonly IDisposable _dependency; private bool _disposed; public DependencyDisposingStreamWrapper(Stream stream, IDisposable dependency) { _stream = stream; _dependency = dependency; } # region - Overrides of all Stream members, delegating to underlying stream - // ... #endregion protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { _dependency.Dispose(); } base.Dispose(disposing); _disposed = true; } } }
source share