Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# IDisposable question

I have the following code example:

public interface IRepository {
   // Whatever
}

public class SampleRepository : IRepository {
   // Implements 'Whatever'
}

public class NHibernateRepository : IRepository, IDisposable {

   // ...

   public void Dispose() { ... }
}

Now - is that really bad? I'm not sure, but this seems to be pretty the same as not marking the destructor of the base class virtual in C++.

I don't want to make the IRepository interface implement IDisposable, because that would bring unwanted complexity and bunch of classes which would also have to implement IDisposable.


How should this case be handled?

I'm sure this can happen to any type hierarchy - when one of the derived type has to manage disposable resources.

So what should I do - pull the IDisposable up to the very first interface or leave it as it and hope user would distinguish disposable and non-disposable repositories?

Thank you.

like image 286
Yippie-Ki-Yay Avatar asked Dec 13 '10 17:12

Yippie-Ki-Yay


1 Answers

Yes, I'd say this is bad - because you can't use all repositories in the same way.

I would personally make the repository interface extend IDisposable - it's easy enough to implement it with a no-op, after all.

This is exactly the same choice as is made by Stream, TextReader and TextWriter in the main framework. StringWriter (for example) doesn't need to dispose of anything... but TextWriter is still disposable.

This all comes about because IDisposable is in some ways an odd interface: it doesn't convey something that is offered to callers... it conveys something which is required of callers (or at least, strongly encouraged with possible issues if you don't go along with it).

like image 100
Jon Skeet Avatar answered Sep 19 '22 13:09

Jon Skeet