Note that there are some explanatory texts on larger screens.

plurals
  1. POIDisposable implementation in C# - is optional disposal of an injected IDisposable OK?
    primarykey
    data
    text
    <p>if I have fairly a standard abstract class which allows injection of an IDisposable instance. However, some classes inheriting from this class should NOT dispose the injected repository, where as others should. The obvious solution is to have a constructor:</p> <pre><code>public abstract class WorkspaceViewModel : IDisposable { readonly bool _cascadeDisposeRepository; protected WorkspaceViewModel(IRepository repository, bool cascadeDisposeRepository=true) { _repository = repository; _cascadeDisposeRepository = cascadeDisposeRepository; } </code></pre> <p><strong>Edit:</strong></p> <p>I also had a constructor with</p> <pre><code> protected WorkspaceViewModel() :this(new RepositoryA(), true){} </code></pre> <p><strong>End Edit</strong></p> <p>and then implement the Dispose method in the <a href="http://msdn.microsoft.com/en-us/library/vstudio/b1yfkh5e%28v=vs.100%29.aspx" rel="nofollow">recomended microsoft manner</a></p> <pre><code>protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { if (_cascadeDisposeRepository) { _repository.Dispose(); } ..... </code></pre> <p>However, I have never seen IDisposable implemented in this way, and was wondering if it is bad practice (and if so, why, and what other solutions are preferable).</p> <p>Thank you for your thoughts.</p> <p><strong>edit:</strong> Mark's comment made me realise the preferable implementation may be without the parameter-less constructor, forcing any classes inheriting from WorkspaceViewModel to create and dispose their own instances (and choose to implement IDisposable), while removing IDisposable from the implemented interfaces for WorkspaceViewModel.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload