I have an interface that describes a specific business logic, i.e.
public interface IFoo { void Bar(); }
I also have several implementations of this interface, such as
public class ConcreteFoo1 : IFoo { public void Bar() {...} } public class ConcreteFoo2 : IFoo, IDisposable { public void Bar() {...} public void Dispose {...} }
Inside the client, I now get an instance of IFoo through dependency injection, so I have no idea which one I get. But I need to make sure that Dispose is called when I get an instance of ConcreteFoo2 and do with it.
I think I have 2 options, but please correct me, if I have more, better.
Has the extension IFoo IDisposable
This is not very convenient, since the implementation of IFoo also requires the implementation of IDisposable. But that allows me to use the syntax {...}.
Require all clients to check for the presence of IDisposable and call it if necessary.
This will simplify the implementation, but will transfer responsibility to the client, who must do something like this.
public void DoStuff() { IFoo foo = ....;
Is there any other / better way to ensure that Dispose () is called deterministic? Is there a pro and con for either of the two approaches?
c # interface idisposable
Stephan hoffmann
source share