How can I get rid of an arbitrary dependency when deleting a stream?

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(); // TODO: Ensure that when the stream we return is disposed, we also dispose of `entry.Archive`. return entry.Open(); } private ZipArchiveEntry GetEntry() { ZipArchive archive = null; try { archive = new ZipArchive(_zipContent.OpenRead(), ZipArchiveMode.Read, false); var entry = archive.GetEntry(_entryName); if (entry == null) { throw new InvalidOperationException("Specified entry was not found in the ZIP archive. " + _entryName); } return entry; } finally { if (archive != null) { archive.Dispose(); } } } } 

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; } } } 
+4
source share
2 answers

Composition instead of inheritance?

The way .NET works with elements such as StreamReader. There is a member property for the underlying thread, not inheritance from the thread.

If you want to work with existing types such as StreamReader / Writer, TCPClient, etc., you will, however, inherit Stream.

+2
source

You will need to create a wrapper. There is no means to notify when a stream is located. Some other types may provide a public event that fires when they are posted, but Stream does not.

0
source

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


All Articles