What is the correct way to recycle an object from which I only have an interface?

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 = ....; //do stuff IDisposable disposable = foo as IDisposable; if(disposable != null) { disposable.Dispose(); } } 

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?

+8
c # interface idisposable
source share

No one has answered this question yet.

See similar questions:

10
Determining whether IDisposable should extend an interface or be implemented in a class that implements the interface
6
How can I ensure the removal of possibly disposable items?

or similar:

2391
What is the best way to iterate over a dictionary?
1688
What is the difference between an interface and an abstract class?
1270
Why not inherit from List <T>?
742
What does it mean to program an interface?
318
Complete / delete template in C #
4
For Microsoft built classes that inherit IDisposable, should I explicitly call Dispose?
4
C # Calling internal methods of an object passed as an interface
3
Why the utility is accessible through the interface
one
Removing unmanaged objects in C #

All Articles